java的HashMap底层是使用数组加链表实现的,而本文章用数组加红黑树实现。
package Hash;
import java.util.TreeMap;
public class hashTable<K,V> {
private TreeMap<K, V>[] hashT;
private int M;
private int size;
public hashTable(int M){
this.M = M;
this.size = 0;
hashT = new TreeMap[M];
for(int i = 0;i < M;i++) {
hashT[i] = new TreeMap<>();
}
}
public hashTable() {
this(91);
}
//&后为了求绝对值。
private int hash(K key) {
return (key.hashCode() & 0x7fffffff) % M;
}
public int size() {
return size;
}
public void add(K key,V value) {
TreeMap<K, V> map = hashT[hash(key)];
if(map.containsKey(key))
map.put(key, value);
else {
map.put(key, value);
size++;
}
}
public V remove(K key) {
TreeMap<K, V> map = hashT[hash(key)];
if(!map.containsKey(key))
throw new IllegalArgumentException("error");
V ret;
ret = map.remove(key);
size--;
return ret;
}
public void set(K key,V value) {
TreeMap<K, V> map = hashT[hash(key)];
if(!map.containsKey(key))
throw new IllegalArgumentException("error");
map.put(key, value);
}
public boolean contain(K key) {
TreeMap<K, V> map = hashT[hash(key)];
return map.containsKey(key);
}
public V get(K key) {
return hashT[hash(key)].get(key);
}
}
实现起来很简单,因为大部分都可以复用TreeMap的方法,不过有一个问题需要注意,因为TreeMap的key是可以进行比较的,而HashMap不需要该要求,所以也算一个bug吧。