package _03;
import java.util.HashMap;
import java.util.Map;
public class _3_14_2Demo {
public static void main(String[] args) {
// Map<Integer,String> map = new HashMap<>();
//
// map.put(1,"one");
// map.put(2,"two");
//
// System.out.println(map.get(1));
// System.out.println(map.size());
// System.out.println(map.isEmpty());
// Map中的键是不能重复的
// 如果有重复,则新的更新旧的
// 键是否重复根据equals方法判断
// Hashmap底层采用了哈希表
// 哈希表的实质其实就是数组加链表
// HashMap的存储键值对的过程: 1. 根据key查找hashcode
// 在JDK8中,当链表长度大于8时,《链表》就转换成红黑树,大大的提高了查找的效率
// HashMap的位桶数组的长度为16,长度超出时进行扩容
myHashMap mhmap = new myHashMap();
// mhmap.put(10,"wei");
// mhmap.put(55,"li");
// mhmap.put(100,"si");
// mhmap.put(10,"li");
mhmap.put(53,"gg");
mhmap.put(69,"hh");
mhmap.put(85,"kk");
System.out.println(mhmap.get(53));
}
}
class myHashMap<k,v>{
Node2[] table;
int size;
public myHashMap(){
table = new Node2[16];
}
public void put(k key,v value){
//定义了新的节点对象
Node2 node = new Node2();
node.hash = myhash(key.hashCode(), table.length);
node.key = key;
node.value = value;
node.next = null;
Node2 nod = table[node.hash];
if(nod == null){
table[node.hash]=node;
size++;
}else{
//遍历链表则找到是否有重复,没有重复则跟在尾部,有重复的则更新。
while(nod.next != null){
if(nod.key.equals(key)){
nod.value = value;
break;
}
nod = nod.next;
}
if(nod.key == key){
nod.value =value;
}else{
nod.next = node;
size++;
}
}
}
public int myhash(int v,int length){
// System.out.println(v&(length-1));
return v&(length-1);
}
public String toString(){
//保存我们的{10:"aa",11:"bb".....}的字符串对
StringBuilder sb = new StringBuilder("{");
//遍历bucket数组
for(int i=0;i<table.length;i++){
Node2 temp = table[i];
if(temp !=null){
//遍历数组
while(temp !=null){
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
}
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
}
public v get(k key){
//根据key对象查找hashcode 然后查找对应的bucket数组,遍历链表
int hashCode = myhash(key.hashCode(), table.length);
Node2 temp = table[hashCode];
if(temp != null){
while(temp != null){
if(temp.key.equals(key)){
return (v)temp.value;
}else{
temp = temp.next;
}
}
return null;
}
return null;
}
}
//用于hashMap中
class Node2<k,v>{
int hash;
k key;
v value;
Node2 next;
}
手写HashMap
于 2022-03-14 14:02:12 首次发布