/*
HashSet的实现原理:
往HashSet添加元素的时候,HashSet会先调用元素的hashCode方法得到元素的哈希值 ,
然后通过元素 的哈希值经过移位等运算,就可以算出该元素在哈希表中 的存储位置。
情况1: 如果算出元素存储的位置目前没有任何元素存储,那么该元素可以直接存储到该位置上。
情况2: 如果算出该元素的存储位置目前已经存在有其他的元素了,那么会调用该元素的equals方法与该位置的元素再比较一次
,如果equals返回的是true,那么该元素与这个位置上的元素就视为重复元素,不允许添加,如果equals方法返回的是false,那么该元素运行添加。
*/
import java.util.*; class Person{
String name;
int id; public Person(String name, int id) {
this.name = name;
this.id = id;
} @Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
} @Override
public int hashCode() { //此时hashCode方法被调用4次
System.out.println("hashCode==============");
return this.id;
} @Override
public boolean equals(Object obj) { ////此时equals方法被调用1次
System.out.println("equals------------");
Person p = (Person) obj;
return this.id == p.id;
} } public class Demo5 {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(new Person("大师兄", 1));
set.add(new Person("二师兄", 3));
set.add(new Person("沙师弟", 2)); //id唯一性,若id相同,就应该为同一人,为此,重写hashCode方法和equals方法
System.out.println("添加成功吗?" + set.add(new Person("师傅", 1))); Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
结果:
hashCode==============
hashCode==============
hashCode==============
hashCode==============
equals------------
添加成功吗?false
Person [name=大师兄, id=1]
Person [name=沙师弟, id=2]
Person [name=二师兄, id=3]
注意,这个是无序、不可重复的
比如:
HashSet set = new HashSet();
set.add(new Person("大师兄", 1));
set.add(new Person("二师兄", 3));
set.add(new Person("沙师弟", 2)); set.add(new Person("大师兄", 43));
set.add(new Person("二师兄", 333));
set.add(new Person("沙师弟", 22));
set.add(new Person("大师兄", 33));
set.add(new Person("二师兄", 344));
set.add(new Person("沙师弟", 211));
此时结果:
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
hashCode==============
equals------------
添加成功吗?false
Person [name=大师兄, id=1]
Person [name=大师兄, id=33]
Person [name=沙师弟, id=2]
Person [name=二师兄, id=3]
Person [name=沙师弟, id=211]
Person [name=沙师弟, id=22]
Person [name=二师兄, id=344]
Person [name=大师兄, id=43]
Person [name=二师兄, id=333]