| HashSet中判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。上述程序中hs集合每次加入新的元素,底层会自动调用hashCode方法,判断两个对象的地址值是否相同,如果不同则视为不同对象,否则会进一步调用equals方法判断对象内容是否相同。这样就会保证HashSet体系中元素的唯一性。 class Person implements Comparable
 {
 private String name;
 private int age;
 Person(String name,int age)
 {
 this.name=name;
 this.age=age;
 }
 public String getName()
 {
 return name;
 }
 public int getAge()
 {
 return age;
 }
 //覆盖父类hashCode算法,按对象条件设定哈希值
 public int hashCode()
 {
 
 //检测是否调用hashCode方法,以及何时调用
 System.out.println(this.name+"...hashcode..."+this.name);
 return name.hashCode()+age;
 }
 //比较每个对象中的名字和年龄
 public boolean equals(Object obj)
 {
 if(!(obj instanceof Person))
 throw new RuntimeException("不是Person对象");
 Person p=(Person)obj;//将Object对象强转成Person
 //检测是否调用equals方法,何时调用
 System.out.println(this.name+"...equals..."+p.name);
 return this.name.equals(p.name) && this.age==p.age;
 }
 public int compareTo(Object obj)
 {
 if(!(obj instanceof Person))
 throw new RuntimeException("不是Person对象");
 Person p=(Person)obj;
 //检测是否调用compareTo方法,何时调用
 System.out.println(this.name+"...zishengcompareto..."+p.name);
 if(this.age>p.age)
 return 1;
 if(this.age==p.age)
 {
 
 //年龄相同继续比较姓名
 return this.name.compareTo(p.name);
 }
 return -1;
 }
 
 }
 class HashSetTest
 {
 public static void hashSet()
 {
 HashSet hs= new HashSet();
 hs.add(new Person("h1",21));
 hs.add(new Person("h2",22));
 hs.add(new Person("h3",23));
 hs.add(new Person("h1",21));
 Iterator it=hs.iterator();
 while(it.hasNext())
 {
 Person p=(Person)it.next();
 System.out.println(p.getName()+"::"+p.getAge());
 }
 }
 }
 |