//定义一个Person类 覆盖hashCode()和equals方法class Person{ private String name; private int age; public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
//定义一个HashCode集合的类
public class HashCodeTest {
public static void main(String[] args) {
Collection <Person> hs=new HashSet<Person>();
Person p1=new Person("1", 10);
Person p2=new Person("2", 12);
Person p3=new Person("3", 13);
Person p4=new Person("1", 10);
System.out.println("修改前"+p1.hashCode());
hs.add(p1);
hs.add(p2);
hs.add(p3);
hs.add(p4);
//添加后改动对象属性(涉及到产生HashCode值的属性),导致删除不成功。
p1.setName("a");
System.out.println("修改后"+p1.hashCode());
hs.remove(p1);//删除也是根据元素HashCode的值来查找和移除。
System.out.println(Arrays.asList(hs)+" "+hs.size());//打印出来的集合还是三个元素,删除失败。
}
}
|