java基础,集合,HashMap,源码解析
最怕,你以为你懂咯,其实你还不懂;
见贤思齐,看看那些我们习以为常的集合,通过相关定义、源码,思考分析,加深对其的理解,提高编码能力,能做一个略懂的程序员;
做几个我们常用的集合类。开篇HashMap
1 private V putForNullKey(V value) { 2 for (Entry<K,V> e = table[0]; e != null; e = e.next) { 3 if (e.key == null) { 4 V oldValue = e.value; 5 e.value = value; 6 e.recordAccess(this); 7 return oldValue; 8 } 9 } 10 modCount++; 11 addEntry(0, null, value, 0); 12 return null; 13 }
1 //初始化大小 2 static final int DEFAULT_INITIAL_CAPACITY = 16; 3 //1左移30位 4 static final int MAXIMUM_CAPACITY = 1 << 30; 5 //临界因子 6 static final float DEFAULT_LOAD_FACTOR = 0.75f; 7 8 9 void addEntry(int hash, K key, V value, int bucketIndex) { 10 if ((size >= threshold) && (null != table[bucketIndex])) { 11 resize(2 * table.length);//长度扩大两倍,进行交换 12 hash = (null != key) ? hash(key) : 0; 13 bucketIndex = indexFor(hash, table.length); 14 } 15 16 createEntry(hash, key, value, bucketIndex); 17 } 18 19 20 void resize(int newCapacity) { 21 Entry[] oldTable = table; 22 int oldCapacity = oldTable.length; 23 if (oldCapacity == MAXIMUM_CAPACITY) { 24 threshold = Integer.MAX_VALUE; 25 return; 26 } 27 28 Entry[] newTable = new Entry[newCapacity]; 29 boolean oldAltHashing = useAltHashing; 30 useAltHashing |= sun.misc.VM.isBooted() && 31 (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); 32 boolean rehash = oldAltHashing ^ useAltHashing; 33 transfer(newTable, rehash); 34 table = newTable; 35 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); 36 } 37 38 //交换元素 39 void transfer(Entry[] newTable, boolean rehash) { 40 int newCapacity = newTable.length; 41 for (Entry<K,V> e : table) { 42 while(null != e) { 43 Entry<K,V> next = e.next; 44 if (rehash) { 45 e.hash = null == e.key ? 0 : hash(e.key); 46 } 47 int i = indexFor(e.hash, newCapacity); 48 e.next = newTable[i]; 49 newTable[i] = e; 50 e = next; 51 } 52 } 53 }
1 public V put(K key, V value) { 2 if (key == null) 3 return putForNullKey(value); 4 int hash = hash(key); 5 int i = indexFor(hash, table.length); 6 for (Entry<K,V> e = table[i]; e != null; e = e.next) { 7 Object k; 8 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 9 V oldValue = e.value; 10 e.value = value; 11 e.recordAccess(this); 12 return oldValue; 13 } 14 } 15 16 modCount++; 17 addEntry(hash, key, value, i); 18 return null; 19 }