class MyHashMap<K,V>{
private Entry<K,V>[] table;
private int size;
private static final int defaultCapacity=8;
@Override
public String toString() {
return "MyHashMap{" +
"table=" + Arrays.toString(table) +
'}';
}
class Entry<K,V>{
private K key;
private V value;
protected Entry<K,V> next;
protected int hash;
public Entry(K key, V value, int hash) {
this.key = key;
this.value = value;
this.hash = hash;
}
@Override
public String toString() {
return "Entry{" +
"key=" + key +
", value=" + value +
", hash=" + hash +
'}';
}
}
public MyHashMap(){
this(defaultCapacity);
}
public MyHashMap(int capacity){
table=new Entry[capacity];
}
public int hash(K key){
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public void put(K key,V value){
int hash=hash(key);
int index=hash & table.length-1;
if(table[index]==null){
table[index]=new Entry<>(key, value, hash);
size++;
}else{
Entry<K,V> firstNode= table[index];
if(firstNode.key.equals(key)){
firstNode.value=value;
}else{
Entry<K,V> currentNode=firstNode;
while(currentNode.next!=null&&!currentNode.key.equals(key)){
currentNode=currentNode.next;
}
if(currentNode.next==null){
if(currentNode.key.equals(key)){
currentNode.value=value;
}else{
currentNode.next= new Entry<>(key,value,hash);
size++;
}
}else{
currentNode.value =value;
}
}
}
}
public V get(K key){
int hash=hash(key);
int index=hash&table.length-1;
Entry<K,V> firstNode=table[index];
if(firstNode==null){
return null;
}else{
Entry<K,V> currentNode=firstNode;
while(currentNode!=null){
if (currentNode.key.equals(key)){
return currentNode.value;
}
currentNode=currentNode.next;
}
}
return null;
}
public boolean remove(K key){
int hash=hash(key);
int index=hash &table.length-1;
Entry<K,V> firstNode=table[index];
if(firstNode==null){
return false;
}else{
if(firstNode.key.equals(key)){
table[index]=firstNode.next;
return true;
}
while(firstNode.next!=null){
if(firstNode.next.key.equals(key)){
firstNode.next=firstNode.next.next;
return true;
}else{
firstNode=firstNode.next;
}
}
}
return false;
}
}
public class HashMapTest {
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>();
map.put("dandan",23);
map.put("xuanxuan",56);
map.put("mengchen",12);
System.out.println(map);
System.out.println(map.get("dandan"));
System.out.println(map.remove("dandan"));
System.out.println(map);
}
}