手写实现一个简单的hashmap
package t1;
public class Test<K, V> {
private Entry[] table;
private static final int CAPCITY = 2;
public void put(K k, V v) {
if (table == null) {
init();
}
int hashCode = hash(k);
int index = indexFor(hashCode);
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == k) {
entry.value = v;
break;
}
}
addEntry(k, v, index);
}
private void addEntry(K k, V v, int index) {
Entry newEntry = new Entry(k, v, table[index]);
table[index] = newEntry;
}
private int indexFor(int hashCode) {
return hashCode % table.length;
}
private int hash(K k) {
return k.hashCode();
}
@SuppressWarnings("unchecked")
private void init() {
table = new Test.Entry[CAPCITY];
}
public V get(K k) {
int hashCode = hash(k);
int index = indexFor(hashCode);
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == k) {
return entry.value;
}
}
return null;
}
class Entry {
public K key;
public V value;
public Entry next;
public Entry(K key, V value) {
super();
this.key = key;
this.value = value;
}
public Entry(K key, V value, Test<K, V>.Entry next) {
super();
this.key = key;
this.value = value;
this.next = next;
}
@Override
public String toString() {
return "Entry [key=" + key + ", value=" + value + ", next=" + next + "]";
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Entry getNext() {
return next;
}
public void setNext(Entry next) {
this.next = next;
}
}
public static void main(String[] args) {
Test<String, String> myHashMap = new Test<>();
myHashMap.put("1", "1v");
myHashMap.put("2", "2v");
myHashMap.put("3", "3v");
myHashMap.put("4", "4v");
myHashMap.put("1", "5v");
System.out.println(myHashMap.get("1"));
}
}
输出结果:


浙公网安备 33010602011771号