Java HashMap实现

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 class Entry<K, V> {
 5     K key;
 6     V value;
 7 
 8     Entry(K key, V value) {
 9         this.key = key;
10         this.value = value;
11     }
12 }
13 
14 public class Myhashmap<K, V> {
15     private static final int DEFAULT_SIZE = 20;
16     private int size = 0;
17     public List<Entry<K, V>>[] array;
18 
19     public Myhashmap() {
20         this.array = new List[DEFAULT_SIZE];
21     }
22 
23     private int hash(K key) {
24         int temp = key.hashCode();
25         return (temp & 0x7FFFFFFF) % array.length;
26     }
27 
28     public void put(K key, V value) {
29         int indice = hash(key);
30         if (array[indice] == null) {
31             array[indice] = new ArrayList<Entry<K, V>>();
32             array[indice].add(new Entry<K, V>(key, value));
33             size++;
34         } else {
35             boolean find = false;
36             for (Entry<K, V> e : array[indice]) {
37                 if (e.key == key) {
38                     e.value = value;
39                     find = true;
40                 }
41             }
42             if (!find) {
43                 array[indice].add(new Entry<K, V>(key, value));
44                 size++;
45             }
46         }
47         if (size >= array.length / 2) {
48             rehash();
49         }
50     }
51 
52     public V get(K key) {
53         int indice = hash(key);
54         if (array[indice] == null) {
55             return null;
56         }
57         for (Entry<K, V> e : array[indice]) {
58             if (e.key == key) {
59                 return (V) e.value;
60             }
61         }
62         return null;
63     }
64 
65     public boolean containsKey(K key) {
66         int indice = hash(key);
67         if (array[indice] == null) {
68             return false;
69         }
70         for (Entry<K, V> e : array[indice]) {
71             if (e.key == key) {
72                 return true;
73             }
74         }
75         return false;
76     }
77 
78     public int size() {
79         return size;
80     }
81 
82     public boolean isEmpty() {
83         return size == 0;
84     }
85 
86     private void rehash() {
87         List<Entry<K, V>>[] cur = new List[2 * array.length];
88         for (int i = 0; i < array.length; i++) {
89             cur[i] = array[i];
90         }
91         array = cur;
92     }
93 }

 

posted @ 2017-10-28 12:31  想做码农的熊孩子  阅读(235)  评论(0编辑  收藏  举报