閒着沒事自己隨便寫了一個類似hashMap得簡單功能代碼,技術有限,僅供參考
對於真正hashMap中用到的,樹形結構以及jdk1.8中的紅黑樹,下面內容未涉及(只是簡單得實現)
hashMap是由數組和鏈表組成得:
首先對於類似鏈表數據得封裝類:MyNode<K,V>
/**
* 模擬鏈表,每個節點上存放key值,value值,以及下個節點的信息
* @author admin
*
* @param <K>
* @param <V>
*/
public class MyNode<K,V> {
private int hash;
private K key;
private V value;
//下一個節點元素
private MyNode<K,V> next;
public int getHash() {
return hash;
}
public void setHash(int hash) {
this.hash = hash;
}
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 MyNode<K, V> getNext() {
return next;
}
public void setNext(MyNode<K, V> next) {
this.next = next;
}
}
對於數組:MyHashMap<K,V>,這裏需要計算,放置得元素所在,數組得位置
public class MyHashMap<K,V> {
private MyNode<K,V>[] node;
public MyHashMap(){
//默認初始化大小16,沒有寫擴容
node=(MyNode<K, V>[])new MyNode[16];
}
//放置元素
public void put(K key,V value){
//計算放置元素得數組下標
int hash = hash(key);
MyNode<K, V> myNode = node[hash];
MyNode<K,V> nextNode=new MyNode<K,V>();
//當前下標下是否有元素
if(myNode!=null){
nextNode=myNode;
MyNode<K,V> nextNodeBak=myNode;
boolean flag=true;
while(nextNode!=null){
//如果key值存在,覆蓋
if(nextNode.getKey().equals(key)){
nextNode.setValue(value);
flag=false;
break;
}
nextNodeBak=nextNode;
nextNode=nextNode.getNext();
}
if(flag){
nextNode=new MyNode<K,V>();
nextNode.setHash(hash);
nextNode.setKey(key);
nextNode.setValue(value);
nextNodeBak.setNext(nextNode);
}else{
//當前下標沒有元素直接放置
nextNode.setHash(hash);
nextNode.setKey(key);
nextNode.setValue(value);
node[hash]=nextNode;
}
}
//取元素
public V get(Object key){
int hash = hash(key);
MyNode<K, V> myNode = node[hash];
MyNode<K,V> nextNode=myNode;
while(nextNode!=null){
if(nextNode.getKey().equals(key)){
return nextNode.getValue();
}else{
nextNode=nextNode.getNext();
}
}
return null;
}
private int hash(Object key){
int h;
int hash=(key == null) ? 0 : (key.hashCode()%16);
return Math.abs(hash); //防止負數
}
}
能力有限,不喜勿噴,歡迎交流。