底层原理Hashmap源码解析实例

Map.java

 1 package com.collection;
 2 
 3 public interface Map<K, V> {
 4     public V put(K k, V v);
 5 
 6     public V get(K k);
 7 
 8     public int size();
 9 
10     interface Entry<K, V> {
11         public K getKey();
12 
13         public V getValue();
14     }
15 }

 

HashMap.java

 1 package com.collection;
 2 
 3 public class HashMap<K, V> implements Map<K, V> {
 4     private Entry<K, V>[] table = null;
 5     private int size = 0;
 6     private static int defaultLength = 16;
 7 
 8     public HashMap() {
 9         table = new Entry[defaultLength];
10     }
11 
12     @Override
13     public V put(K k, V v) {
14         int index = hash(k);
15         Entry<K, V> entry = table[index];
16         if (entry == null) {
17             table[index] = new Entry<K, V>(k, v, null, index);
18             size++;
19         } else {
20             table[index] = new Entry<K, V>(k, v, entry, index);
21         }
22         return table[index].getValue();
23     }
24 
25     private int hash(K k) {
26         int index = k.hashCode() & (defaultLength - 1);
27         return Math.abs(index);
28     }
29 
30     @Override
31     public V get(K k) {
32         if (size == 0) {
33             return null;
34         }
35         int index = hash(k);
36         Entry<K, V> entry = getEntry(k, index);
37 
38         return entry == null ? null : entry.getValue();
39     }
40 
41     private Entry<K, V> getEntry(K k, int index) {
42         for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
43             if (entry.hash == index && (k == entry.getKey() || k.equals(entry.getKey()))) {
44                 return entry;
45             }
46         }
47         return null;
48     }
49 
50     @Override
51     public int size() {
52         return 0;
53     }
54 
55     class Entry<K, V> implements Map.Entry<K, V> {
56         K k;
57         V v;
58         Entry<K, V> next;
59         int hash;
60 
61         public Entry(K k, V v, Entry<K, V> next, int hash) {
62             this.k = k;
63             this.v = v;
64             this.next = next;
65             this.hash = hash;
66         }
67 
68         @Override
69         public K getKey() {
70             return k;
71         }
72 
73         @Override
74         public V getValue() {
75             return v;
76         }
77     }
78 }

TestHashMap.java

 1 package com.collection;
 2 
 3 public class TestHashMap {
 4     public static void main(String[] args) {
 5         com.collection.HashMap map = new com.collection.HashMap<>();
 6 
 7 
 8         for (int i = 0; i < 6666; i++) {
 9             map.put("Monkey" + i, "計算方法的事實");
10             System.out.println(map.get("Monkey"));
11         }
12 
13         System.out.println(map);
14 
15     }
16 }

 

posted @ 2019-04-19 16:24  chenxiangxiang  阅读(109)  评论(0编辑  收藏