簡單實現HashMap中數組 + 鏈表
- 新建數組,
- 添加的元素下標 爲 hashCode % 數組長度
- 裏面存儲自定義節點對象,下標值相同的存儲到next中,依次向下存儲
public class MyHashMap<K, V> {
//節點數組
private Entry<K, V>[] table;
//定義初始數組容量
private static Integer CAPACITRY = 5;
//元素數量
private Integer size = 0;
//封裝一個節點
class Entry<K, V> {
private K k;
private V v;
private Entry<K, V> next;
public Entry(K k, V v, Entry<K, V> next) {
this.k = k;
this.v = v;
this.next = next;
}
@Override
public String toString() {
return this.k+"-"+this.v+"-"+ this.next;
}
}
public MyHashMap() {
//自定義一個數組進行存放元素
this.table = new Entry[CAPACITRY];
}
public int size() {
return size;
}
public V get(K key) {
Integer hash = key.hashCode();
Integer index = hash % table.length;
for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
if (key.equals(entry.k)) {
return entry.v;
}
}
return null;
}
public Object put(K key, V value) {
Integer hash = key.hashCode();
System.out.println("hash=="+hash);
//下標 哈希值 對 數組長度 取模
//下標值爲 0 - 數組長度的值 這樣能分配數組
Integer index = hash % table.length;
//覆蓋舊Value
for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
if (key.equals(entry.k)) {
//V oldValue = entry.v;
entry.v = value;
//return oldValue;
}
}
//存儲節點對象 節點對象中存儲着key和value 並且含有指針指向head
addEntry(key, value, index);
return null;
}
private void addEntry(K key, V value, Integer index) {
System.out.println(table[index]);
table[index] = new Entry<>(key, value, table[index]);
size++;
}
public static <V, K> void main(String[] args) {
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1,"張三1");
myHashMap.put(2,"張三2");
myHashMap.put(3,"張三3");
myHashMap.put(4,"張三4");
myHashMap.put(5,"張三5");
myHashMap.put(6,"張三6");
}
}