Java手写简易版HashMap的使用(存储+查找)
HashMap的基本结构
package com.liuyuhe; public class Node { int hash; Object key; Object value; Node next; }
package com.liuyuhe; public class MyHashMap { Node[] table; //位桶数组 int size; //存放键值对的个数 public MyHashMap() { table=new Node[16]; } }
put()方法存储键值对
public void put(Object key,Object value) { Node newNode = new Node(); newNode.hash=myHash(key.hashCode(),table.length); newNode.key=key; newNode.value=value; newNode.next=null; Node temp = table[newNode.hash]; Node iterLast=null; if(temp==null) { table[newNode.hash]=newNode; }else { while(temp!=null) { if(temp.key.equals(key)) { temp.value=value; return; }else { iterLast=temp; temp=temp.next; } } iterLast.next=newNode; } ++size; } public int myHash(int v,int length) { System.out.println("hash in myHash: "+(v&(length-1))); return v&(length-1); }
重写toString()方法打印Map内容
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); boolean isFirst=true; //遍历数组 for(int i=0;i<table.length;++i) { //遍历链表 Node temp = table[i]; while(temp!=null) { if(isFirst) { isFirst=false; sb.append(temp.key+":"+temp.value); }else { sb.append(","+temp.key+":"+temp.value); } temp=temp.next; } } sb.append("}"); return sb.toString(); }
get()方法查找键值对
public Object get(Object key) { int hash=myHash(key.hashCode(),table.length); Object value=null; if(table[hash]!=null) { Node temp=table[hash]; while(temp!=null) { if(temp.key.equals(key)) { value=temp.value; break; }else { temp=temp.next; } } } return value; }
增加泛型(完整代码)
package com.liuyuhe; public class Node<K,V> { int hash; K key; V value; Node next; }
package com.liuyuhe; public class MyHashMap<K,V> { Node[] table; //位桶数组 int size; //存放键值对的个数 public MyHashMap() { table=new Node[16]; } public void put(K key,V value) { Node newNode = new Node(); newNode.hash=myHash(key.hashCode(),table.length); newNode.key=key; newNode.value=value; newNode.next=null; Node temp = table[newNode.hash]; Node iterLast=null; if(temp==null) { table[newNode.hash]=newNode; }else { while(temp!=null) { if(temp.key.equals(key)) { temp.value=value; return; }else { iterLast=temp; temp=temp.next; } } iterLast.next=newNode; } ++size; } @SuppressWarnings("unchecked") public V get(K key) { int hash=myHash(key.hashCode(),table.length); V value=null; if(table[hash]!=null) { Node temp=table[hash]; while(temp!=null) { if(temp.key.equals(key)) { value=(V)temp.value; break; }else { temp=temp.next; } } } return value; } public int myHash(int v,int length) { System.out.println("hash in myHash: "+(v&(length-1))); return v&(length-1); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); boolean isFirst=true; //遍历数组 for(int i=0;i<table.length;++i) { //遍历链表 Node temp = table[i]; while(temp!=null) { if(isFirst) { isFirst=false; sb.append(temp.key+":"+temp.value); }else { sb.append(","+temp.key+":"+temp.value); } temp=temp.next; } } sb.append("}"); return sb.toString(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)