package cn.itcast;
public class MyMap01 {
private Node[] table;
public MyMap01(){
this.table = new Node[16];
}
public void put(Object key,Object value){
int hash = MyHash(key);
Node newnode = new Node(key, value, hash);
Node linked = table[hash];
if(linked == null){
table[hash]=newnode;
}else{
while(linked!=null){
if(linked.getKey().equals(key)){
linked.setValue(value);
}else{
if(linked.getNext()==null){
linked.setNext(newnode);
}
}
linked=linked.getNext();
}
}
}
public Object get(Object key){
int hash = MyHash(key);
Node linked = table[hash];
if (linked == null)throw new RuntimeException("key 不存在: "+key);
while(!key.equals(linked.getKey())){
linked=linked.getNext();
}
return linked.getValue();
}
public int MyHash(Object key){
int hashCode = key.hashCode();
int hash = hashCode & (this.table.length - 1);
System.out.println(hash);
return hash;
}
public static void main(String[] args) {
MyMap01 myMap = new MyMap01();
myMap.put(10,"aa");
myMap.put(20,"bb");
myMap.put(30,"cc");
myMap.put(30,"dd");
myMap.put(40,"66666");
myMap.put(90,"66666");
System.out.println(myMap.get(30));
}
}
尝试自定义HashMap
最新推荐文章于 2024-02-11 02:00:00 发布