集合框架之HashSet如何保证元素唯一性的原理 一:HashSet原理 二:将自定义类的对象存入HashSet去重复 三:ecplise自动重写hashCode()和equals()方法解读

我们使用Set集合都是需要去掉重复元素的, 如果在存储的时候逐个equals()比较, 效率较低,哈希算法提高了去重复的效率, 降低了使用equals()方法的次数
当HashSet调用add()方法存储对象的时候, 先调用对象的hashCode()方法得到一个哈希值, 然后在集合中查找是否有哈希值相同的对象
如果没有哈希值相同的对象就直接存入集合
如果有哈希值相同的对象, 就和哈希值相同的对象逐个进行equals()比较,比较结果为false就存入, true则不存

二:将自定义类的对象存入HashSet去重复

类中必须重写hashCode()和equals()方法
hashCode(): 属性相同的对象返回值必须相同, 属性不同的返回值尽量不同(提高效率)
equals(): 属性相同返回true, 属性不同返回false,返回false的时候存储(注意存储自定义对象去重时必须同时重写hashCode()和equals()方法,因为equals方法是按照对象地址值比较的)

三:ecplise自动重写hashCode()和equals()方法解读

 1   /*
 2      * 为什么是31? 1:31是一个质数 2:31个数既不大也不小 3:31这个数好算,2的五次方减一
 3      */
 4     @Override
 5     public int hashCode() {
 6         final int prime = 31;
 7         int result = 1;
 8         result = prime * result + ((name == null) ? 0 : name.hashCode());
 9         result = prime * result + ((sex == null) ? 0 : sex.hashCode());
10         return result;
11     }
12 
13     @Override
14     public boolean equals(Object obj) {
15         if (this == obj)// 调用的对象和传入的对象是同一个对象
16             return true;// 直接返回true
17         if (obj == null)// 传入的对象为null
18             return false;// 返回false
19         if (getClass() != obj.getClass())// 判断两个对象的字节码文件是否是同一个对象
20             return false;// 如果不是返回false
21         Person other = (Person) obj;// 向下转型
22         if (name == null) {
23             if (other.name != null)
24                 return false;
25         } else if (!name.equals(other.name))
26             return false;
27         if (sex == null) {
28             if (other.sex != null)
29                 return false;
30         } else if (!sex.equals(other.sex))
31             return false;
32         return true;
33     }