java 17 -2 set集合以及hashCode()的源码


Collection
  |--List
  有序(存储顺序和取出顺序一致),可重复
  |--Set
  无序(存储顺序和取出顺序不一致),唯一

  HashSet:它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。
  注意:虽然Set集合的元素无序,但是,作为集合来说,它肯定有它自己的存储顺序,
  而你的顺序恰好和它的存储顺序一致,这代表不了有序,你可以多存储一些数据,就能看到效果。

 

set集合:

 1 import java.util.HashSet;
 2 import java.util.Set;
 3 public class SetDemo {
 4 public static void main(String[] args) {
 5 // 创建集合对象
 6 Set<String> set = new HashSet<String>();
 7 
 8 // 创建并添加元素
 9 set.add("hello");
10 set.add("java");
11 set.add("world");
12 set.add("java");
13 set.add("world");
14 
15 // 增强for
16 for (String s : set) {
17 System.out.println(s);
18 }
19 }
20 }

 

hashCode()源码:

 1 interface Collection {
 2 ...
 3 }
 4 
 5 interface Set extends Collection {
 6 ...
 7 }
 8 
 9 class HashSet implements Set {
10 private static final Object PRESENT = new Object();
11 private transient HashMap<E,Object> map;
12 
13 public HashSet() {
14 map = new HashMap<>();
15 }
16 
17 public boolean add(E e) { //e=hello,world
18 return map.put(e, PRESENT)==null;
19 }
20 }
21 
22 class HashMap implements Map {
23 public V put(K key, V value) { //key=e=hello,world
24 
25 //看哈希表是否为空,如果空,就开辟空间
26 if (table == EMPTY_TABLE) {
27 inflateTable(threshold);
28 }
29 
30 //判断对象是否为null
31 if (key == null)
32 return putForNullKey(value);
33 
34 int hash = hash(key); //和对象的hashCode()方法相关
35 
36 //在哈希表中查找hash值
37 int i = indexFor(hash, table.length);
38 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
39 //这次的e其实是第一次的world
40 Object k;
41 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
42 V oldValue = e.value;
43 e.value = value;
44 e.recordAccess(this);
45 return oldValue;
46 //走这里其实是没有添加元素
47 }
48 }
49 
50 modCount++;
51 addEntry(hash, key, value, i); //把元素添加
52 return null;
53 }
54 
55 transient int hashSeed = 0;
56 
57 final int hash(Object k) { //k=key=e=hello,
58 int h = hashSeed;
59 if (0 != h && k instanceof String) {
60 return sun.misc.Hashing.stringHash32((String) k);
61 }
62 
63 h ^= k.hashCode(); //这里调用的是对象的hashCode()方法
64 
65 // This function ensures that hashCodes that differ only by
66 // constant multiples at each bit position have a bounded
67 // number of collisions (approximately 8 at default load factor).
68 h ^= (h >>> 20) ^ (h >>> 12);
69 return h ^ (h >>> 7) ^ (h >>> 4);
70 }
71 }
72 
73 
74 hs.add("hello");
75 hs.add("world");
76 hs.add("java");
77 hs.add("world");
78 
79  
80 
81  

 

posted @ 2016-09-23 20:16  卡拉瓦  阅读(309)  评论(0编辑  收藏  举报