HashSet实现原理

/*

HashSet的实现原理:
  往HashSet添加元素的时候,HashSet会先调用元素的hashCode方法得到元素的哈希值 ,
  然后通过元素 的哈希值经过移位等运算,就可以算出该元素在哈希表中 的存储位置。

情况1: 如果算出元素存储的位置目前没有任何元素存储,那么该元素可以直接存储到该位置上。

情况2: 如果算出该元素的存储位置目前已经存在有其他的元素了,那么会调用该元素的equals方法与该位置的元素再比较一次
      ,如果equals返回的是true,那么该元素与这个位置上的元素就视为重复元素,不允许添加,如果equals方法返回的是false,那么该元素运行添加。

*/

 1 import java.util.*;
 2 
 3 class Person{
 4     String name;
 5     int id;
 6     
 7     public Person(String name, int id) {
 8         this.name = name;
 9         this.id = id;
10     }
11 
12     @Override
13     public String toString() {
14         return "Person [name=" + name + ", id=" + id + "]";
15     }
16 
17     @Override
18     public int hashCode() { //此时hashCode方法被调用4次
19         System.out.println("hashCode==============");
20         return this.id;
21     }
22     
23     @Override
24     public boolean equals(Object obj) { ////此时equals方法被调用1次
25         System.out.println("equals------------");
26         Person p = (Person) obj;
27         return this.id == p.id;
28     }
29     
30 }
31 
32 public class Demo5 {
33     public static void main(String[] args) {
34         HashSet set = new HashSet();
35         set.add(new Person("大师兄", 1));
36         set.add(new Person("二师兄", 3));
37         set.add(new Person("沙师弟", 2));
38         
39         //id唯一性,若id相同,就应该为同一人,为此,重写hashCode方法和equals方法
40         System.out.println("添加成功吗?" + set.add(new Person("师傅", 1)));
41         
42         Iterator it = set.iterator();
43         while(it.hasNext()){
44             System.out.println(it.next());
45         }
46     }
47 }

结果:

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]
原文地址:https://www.cnblogs.com/shadowdoor/p/6816294.html