package cn.cp; //在HashSetTest1的基础上重写hashCode()和equals()方法,来确保对象唯一性 import java.util.HashSet; import java.util.Iterator; class Boy2 { private int age; private String name; public Boy2(int age, String name) { super(); this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } @Override public int hashCode() {//返回新的hash值 return name.hashCode()+age; } @Override public boolean equals(Object obj) { Boy2 b=(Boy2) obj; boolean result=this.age==b.age&&this.name.equals(b.name); return result; } @Override public String toString() { return "boy3 [age=" + age + ", name=" + name + "]"; } } public class HashSetTest2 { public static void main(String[] args) { Boy2 boy1=new Boy2(12, "liming"); Boy2 boy2=new Boy2(13, "liming"); Boy2 boy3=new Boy2(12, "liming"); HashSet hashSet=new HashSet(); hashSet.add(boy1); hashSet.add(boy2); hashSet.add(boy3); Iterator iterator=hashSet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
时间: 2024-10-02 06:53:35