public class HashSetDemo { public static void main(String[] args){ method_01(); } public static void method_01(){ /* toString()方法public String toString() 该方法返回一个字符串,它的值等于: getClass().getName() + '@' + Integer.toHexString(hashCode()) */ HashSet ts=new HashSet(); ts.add(new Person("a", 12)); ts.add(new Person("b", 12)); System.out.println(ts.size()); } }class Person{ private String name; private int age; public Person(String name,int age){ this.name=name; this.age=age; } @Override //覆写父类的方法 public int hashCode() { System.out.println("hashCode---->1"); return 1; } @Override public boolean equals(Object obj) { if(!(obj instanceof Person)) return false; //如果obj不是Person的实例,返回false Person P1=(Person)obj; System.out.println(this.age+"..equlas.."+P1.age); return this.name.equals(P1.name)&&this.age==P1.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; } }