定义:是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。
运算限制:没有限制,这个就是挂腊肠。数组的元素定义为链表,也就是一个横着的数组,每个下标位置挂着一个链表。
基本运算:
1,添加。
2:取值。
定义一个节点数组,由于数组长度有限,所以用传入的key对数组长度取余数,这个余数(hash)就是新节点在数组中的下标,当下标处没有节点,就把新节点放在下标处,如果下标处有节点,比较key是否相等,相等就替换掉,不相等就让新节点成为下标节点的next节点,再有就是next节点的next节点,所以节点定义需要有,key,value,hash,next节点。hash用来定位下标,key用来比较是不是同一个,value是要保存的值,next是不同key取到了同hash存放节点的位置。比如数组长度4,key为6时hash为6除以4余2,key为10时hash为10除以4余2,那么6先来占据了数组下标2,10后来,hash也是2,那就只能挂在6节点的next上面。
取值也是一样,进来先用key取hash找数组下标,然后循环节点链找到key等于传入key的节点。
key为null时hash取0。再来key为null时会替换掉原来的,所以key可以有一个null,而value可以有多个null。
看代码吧
public class HashTable {
private int size ;
private Node[] array ;
public HashTable(int initSize){
this.size = initSize ;
this.array = new Node[size];
}
private int hash(Integer key){
return (key==null?0:(key % size)) ;
}
public void put(Integer key,String value){
int hash = hash(key);
if(array[hash] == null){
array[hash] = new Node(key, value, hash);
}else if(array[hash].key==key || (array[hash].key!=null && array[hash].key.equals(key))){
array[hash].value = value;
}else{
Node aNode = array[hash].next;
while(true){
if(aNode != null){
aNode = array[hash].next ;
if(aNode.key==key || (aNode.key!=null && aNode.key.equals(key))){
aNode.value = value ;
break;
}
}else{
aNode = new Node(key, value, hash);
array[hash].next = aNode ;
break ;
}
}
}
}
public String get(Integer key){
int hash = hash(key);
if(array[hash] == null){
return null ;
}else{
Node node = array[hash] ;
while(true){
if(node==null){
return null ;
}else if(node.key==key || (node.key!=null && node.key.equals(key))){
return node.value ;
}else {
node =node.next;
}
}
}
}
static class Node{
Integer key ;
String value ;
Integer hash ;
Node next ;
public Node(){}
public Node(Integer key,String value,Integer hash ){
this.key = key;
this.value = value;
this.hash = hash;
}
}
public static void main(String[] args) {
HashTable table = new HashTable(10);
table.put(null, "a0");
table.put(1, "b0");
table.put(10, "a1");
table.put(11, "b1");
System.out.println(table.get(null));
System.out.println(table.get(1));
System.out.println(table.get(10));
System.out.println(table.get(11));
System.out.println(table.get(2));
table.put(null, "a2");
table.put(1, "b2");
table.put(10, "a3");
table.put(11, "b3");
System.out.println(table.get(null));
System.out.println(table.get(1));
System.out.println(table.get(10));
System.out.println(table.get(11));
System.out.println(table.get(2));
}
}
运行结果
a0
b0
a1
b1
null
a2
b2
a3
b3
null