手写一个简易的hashMap,包含put、set和size功能(数组+链表)
Java code
/**
* @author wilsonM
* @date 2021年04月20日 3:38 下午
* @description
*/
public class MyHashMapTest<K, V> {
private int size = 0;
private static int DEFAULT_CAPACITY = 1 << 4;
private Entry<K, V>[] table;
private MyHashMapTest() {
table = new Entry[DEFAULT_CAPACITY];
}
private int size() {
return size;
}
private V put(K key, V value) {
int index = getIndex(key);
//todo 注意这个地方的node一定要加泛型 不加泛型的value返回类型是Object
for (Entry<K, V> node = table[index]; node != null; node = node.next) {
//注意这个地方是那key进行equals
//todo 针对put两次key为null的情景
if (node.k == null || node.k.equals(key)) {
V oldValue = node.v;
node.v = value;
return oldValue;
}
}
//这是链表上没有值的情况
table[index] = new Entry<K, V>(key, value, null);
size++;
return value;
}
public V get(K key) {
int index = getIndex(key);
//todo get 注意对table[0]的处理
if (index == 0) {
return table[0] != null ? table[0].v : null;
}
//todo 注意这个地方的node一定要加泛型
for (Entry<K, V> node = table[index]; node != null; node = node.next) {
if (node.k.equals(key)) {
return node.v;
}
}
return null;
}
//注意null值的处理
private int getIndex(K key) {
return key != null ? key.hashCode() & (DEFAULT_CAPACITY - 1) : 0;
}
//链表
class Entry<K, V> {
K k;
V v;
Entry<K, V> next;
public Entry(K k, V v, Entry<K, V> next) {
this.k = k;
this.v = v;
this.next = next;
}
public K getK() {
return k;
}
public V getV() {
return v;
}
public Entry<K, V> getNext() {
return next;
}
}
public static void main(String[] args) {
MyHashMapTest hashMap = new MyHashMapTest();
hashMap.put(null, "meng");
System.out.println("=======" + hashMap.get(null));
hashMap.put(null, "zhao");
System.out.println("=======" + hashMap.get(null));
hashMap.put("1", "lu");
System.out.println("=======" + hashMap.get("1"));
hashMap.put("2", "ze");
System.out.println("=======" + hashMap.get("2") + " size:" + hashMap.size());
hashMap.put("3", "quan");
System.out.println("=======" + hashMap.get("3"));
hashMap.put("1", "lzq");
System.out.println("=======" + hashMap.get("1") + " size:" + hashMap.size());
}
}