JAVA手写实现简单的哈希表
说明:map在日常的开发和学习中非常重要,因为他的插入效率和查找效率以及删除效率都接近于O(1),拿hashtable来说,底层是依赖数组,数组根据下表查找删除插入都是O(1)。
实现分析
哈希表重要一个步骤就是实现哈希函数,根据哈希函数生成对应哈希值,根据哈希值往数组中插入或者删除,查询对应的值。所以关键就在于哈希函数的实现,以及解决哈希冲突。
实现背景
一个班级,同学们有学号,学号的类型为1611001,1611002,16110xx,根据这个特点我只需要截取后两位不同的哈希函数,但是限制100人一类,下一次,将会更新完整的哈希表,主要实现哈希的核心。
哈希函数的编写
由于学号的后两位不同,所以我们可以截取后两位的值,转化整对应int值。
public int hash(String id) {
String lastTowChars=id.substring(id.length()-2,id.length());
int hashValue=Integer.parseInt(lastTowChars);
return hashValue;
}
实现代码的完成过程
public class MyHashTable {
private String[] str=new String[5];
public int hash(String id) {
String lastTowChars=id.substring(id.length()-2,id.length());
int hashValue=Integer.parseInt(lastTowChars);
return hashValue;
}
public boolean insertValue(String key,String value) {
try {
int strMark=hash(key);
str[strMark]=value;
return true;
} catch (Exception e) {
// TODO: handle exception
return false;
}
}
public String searchValueByKey(String key) {
int hash = hash(key);
return str[hash];
}
}
在Main方法中测试
public class myMain {
public static void main(String[] args) {
MyHashTable mht=new MyHashTable();
mht.insertValue("0001", "superpopo");
mht.insertValue("0002", "hahaha");
mht.insertValue("0003", "gagaga");
System.out.println(mht.searchValueByKey("0001"));
System.out.println(mht.searchValueByKey("0002"));
System.out.println(mht.searchValueByKey("0003"));
}
}