今天接着昨天的进度参考网络完成了红黑树实现哈希表的学习与练习其代码如下:
package Hash;
import java.util.TreeMap;
public class HashTable<K,V> {
private TreeMap<K,V>[] hashtable;//哈希表元素个数
private int size;//哈希表长度
private int M;
public HashTable(int M){
this.M=M;
size=0;
hashtable=new TreeMap[M];//开辟空间
for(int i=0;i<M;i++){
hashtable[i]=new TreeMap<>();
}
}//实例化
public HashTable(){
this(97);
}
private int hash(K key){
return (key.hashCode()&0x7fffffff)%M;
}
public int getSize(){
return size;
}
public void add(K key, V value){
TreeMap<K,V>map=hashtable[hash(key)];
if(map.containsKey(key)){
map.put(key,value);//改值
}else{
map.put(key,value);
size++;//加值
}
}
public V remove(K key){
V ret=null;
TreeMap<K,V>map=hashtable[hash(key)];
if(map.containsKey(key)){
ret=map.remove(key);
size--;
}
return ret;
}
public void set (K key,V value){
TreeMap<K,V>map=hashtable[hash(key)];
if(!map.containsKey(key)){
throw new IllegalArgumentException(key+"dosn't exist");
}
map.put(key,value);
}
public boolean contains(K key){
return hashtable[hash(key)].containsKey(key);
}
public V get(K key){
return hashtable[hash(key)].get(key);
}
}
明天计划开始着手假期作业-----安卓记账本开发学习(安装、初识所需软件等)。
浙公网安备 33010602011771号