1.我对hashmap的定义
一个按key值作为索引存储使用的数组
2.实现方法
首先根据对象的哈希值通过散列计算将其映射到一段地址单元(或者说是数组中的不同位置),计算方法:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
此处带来了问题:无论多么理想的散列函数,一旦存放对象多于数组的长度,总会有两个对象的哈希值相同,解决的方法参考ArrayList,可采用开放定址法或者链表法解决冲突问题。
java中采用链表法解决冲突,先来看API中对节点的定义:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
每个节点对象都存有该节点的k值,value以及下一节点对象的引用(可以认为是指针啦),发生冲突时,后来的对象就挂在该地址对应链表的末端。对hashmap进行的put,get等操作就转化为了对链表的操作。到此,我们就可以写一个自己的哈希表了。
3.我的hashmap实现
前面提到解决冲突的方法有两种,那么就会写出两种hashmap,那为什么不写一个同一的接口,让两种hashmap去实现,这样在使用的时候两个就可以通过接口统一调用了(。_。)
public interface MyHashTable {
boolean insert(Object theKey,Object obj);
Object Search(Object theKey);
boolean delete(Object theKey);
int size();
int capacity();
boolean isEmpty();
void clear();
void output();
}
接口定义了常用的操作。
采用链表存储的方法:
private int m;//散列表的容量
private HashNode[] ht;//保存散列表的数组;
private int n;//已有元素的个数
private int count=0;
public boolean insert(Object theKey, Object obj) {
int d=h(theKey);
//找到散列表中相应链表的表头地址
HashNode p=ht[d];
//遍历链表
while(p!=null){
if(p.key.equals(theKey))
break;
else
p=p.next;
}
if(p!=null){
p.element=obj;
return false;
}
else{
//创建新节点并插入到相应链表的表头
p=new HashNode(theKey, obj);
p.next=ht[d];
ht[d]=p;
n++;
return true;
}
}
采用开放定址法解决的:
public boolean insert(Object theKey, Object obj) {
int d=h(theKey);
int temp=d;
while(key[d]!=null&&!key[d].equals(tag)){
if(key[d].equals(theKey))
break;
d=(d+1)%m; //可采用d=d+2*i-1
if(d==temp){
//查了一圈还没空间,是时候扩容了
System.out.println("散列表已满");
System.exit(1);
}
}
//返回true则原散列表无该键值
if(key[d]==null||key[d].equals(tag)){
key[d]=theKey;
ht[d]=obj;
n++;
return true;
}
else{
ht[d]=obj;
return false;
}
4.我与官方版的较量
那就比一比试试吧:
再试:
完败给官方,具体的差别分析那就写在下一篇吧。。不过也有一个有意思的事,就算是官方的每次运行时间也都不一样(每次分配的内存位置不同,冲突次数什么的也会变吧)。
本人第一次写博客,还请各位大佬指点。。