闲着没事自己随便写了一个类似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); //防止负数
}
}
能力有限,不喜勿喷,欢迎交流。