HashMap的底层是由数组+链表来实现的,其中数组是用来储存元素的,链表则是用来解决hash冲突的。put元素的时候,如果key值未发生hash冲突,则依次放入数组,如果key值发生hash冲突,则把被冲突的那个元素作为链表的头节点,要存入的元素作为子节点进行存放。即链表里存储的都是hash值一样,key不一样的节点。
懂了底层的实现,在不考虑Hash算法以及如何减少hash碰撞的情况下,我们可以简单的实现HashMap的put()和get()。
public class Node{
K key;
V value;
int hash;
Node next;
public Node(K key,V value,int hash,Node next){
this.key = key; this.value = value; this.hash = hash; this.next=next
}
}
public class NodeArray{
private Node[] nodeArr;
private int size;
public NodeArray(int capacity){
nodeArr = new Node[capacity];
this.size=0;
}
public void addNode(Node e){
nodeArr[size]=e;
size++;
}
public int getSize(){
return size;
}
}
public class Map{
int capaticy=30;
NodeArr arr = new NodeArr(capaticy);
public void put(K key,V value,int hash){
if(arr.size==0){
arr.add(new Node(key,value,hash,null));
}else{
boolean hashClash = false;
Node currNode = null;
for(int i=0;i<arr.length;i++){
if(arr[i].hash==hash){ //如果发生了hash冲突
hashClash = true;
while(arr[i].next!=null){
currNode = arr[i].next;
if(currNode.key.equals(key)){
currNode.value = value; //并且key还一样,则覆盖value的值
return;
}
}
currNode.next = new Node(key,value,hash,null);
}
}
if(!hashClash){
arr.add(new Node(key,value,hash,null));
}
}
}
public void get(K key,int hash){
Node currNode = null;
for(int i =0;i<arr.length;i++){
if(arr[i].hash == hash){
currNode=arr[i];
break;
}
}
if(currNode.next==null){
return currNode.value;
}else{
if(currNode.key==kye){
return currNode.value;
}
while(currNode.next!=null){
currNode = currNode.next;
if(currNode.key==kye){
return currNode.value;
}
}
}
}
}