1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
| public class MyHashMap<K,V> { private Node<K,V>[] table;
private final int DEFAULT_INITIAL_CAPACITY=1<<4;
private int size=0;
private static final float DEFAULT_FACTOR=0.75f;
private int threshold;
public MyHashMap(){ this.table = new Node[DEFAULT_INITIAL_CAPACITY]; threshold = (int) (table.length*DEFAULT_FACTOR); }
public int size(){ return this.size; }
public V get(K k){ int index = index(table.length, k); Node<K, V> node = table[index]; if (node==null){ return null; } if ( node.getNext() ==null ){ return node.getV(); } else { Node<K,V> next = node.next; while (next!=null){ if (node.getK().equals(k)){ return node.getV(); } next=next.next; } } return null; }
public void put(K k,V v){ int index = index(table.length, k); Node<K, V> node = table[index]; if (node==null){ table[index] = new Node<>(hash(k),k,v,null); size++; return; } if (node.getK().equals(k)){ node.setV(v); return; } Node<K,V> newNode = new Node<>(); newNode.setV(v); newNode.setK(k); newNode.setNext(node); table[index] = newNode; size++; System.out.println("元素个数:"+size+",负载阈值:"+threshold+",node数组的容量:"+table.length); if (size>threshold){ resize(); } }
private void resize(){ Node[] tableOle = table; Node[] tableNew = new Node[tableOle.length<<1]; for (int i = 0; i < tableOle.length; i++) { if (tableOle[i]!=null){ int newIndex = index(tableNew.length, tableOle[i].hash); tableNew[newIndex] = tableOle[i]; } } table = tableNew; threshold = (int) (tableNew.length*DEFAULT_FACTOR); }
static final int hash(Object key){ int h = key.hashCode(); return (key == null) ? 0 : (h ^ (h >> 16)); }
static int index(int n,Object key){ return (n-1)&hash(key); }
class Node<K,V>{ int hash; K k; V v; Node<K,V> next;
public Node() { }
public Node(int hash, K k, V v, Node<K, V> next) { this.hash = hash; this.k = k; this.v = v; this.next = next; }
@Override public String toString() { return "Node{" + "hash=" + hash + ", k=" + k + ", v=" + v + ", next=" + next + '}'; }
public int getHash() { return hash; }
public void setHash(int hash) { this.hash = hash; }
public K getK() { return k; }
public void setK(K k) { this.k = k; }
public V getV() { return v; }
public void setV(V v) { this.v = v; }
public Node<K, V> getNext() { return next; }
public void setNext(Node<K, V> next) { this.next = next; } } }
|