进行hashmap原理解析
手写一个简单的hashMap
hashmap的底层运行是数组加链表
链表就是为了解决哈希碰撞的情况
public class hashMap {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("曹操","曹操");
hashMap.put("刘备","刘备");
hashMap.put("孙权","孙权");
hashMap.put("赵云","赵云");
hashMap.put("关羽","关羽");
hashMap.put("张飞","张飞");
// System.out.println(hashMap.get("史子峻"));
for(String key:hashMap.keySet()){
int hash = key.hashCode();
//赵云的hash值是 1142716,index is 1我们变短一点,我们取模
int index = hash % 15;
System.out.println(String.format("%s的hash值是 %s,index is %s",key,hash,index));
}
}
}
关羽的hash值是 679082,index is 2
孙权的hash值是 751370,index is 5
张飞的hash值是 794046,index is 6
刘备的hash值是 674287,index is 7
曹操的hash值是 842996,index is 11
赵云的hash值是 1142716,index is 1
Process finished with exit code 0