版权声明: https://blog.csdn.net/weixin_40072979/article/details/82964096
//根据key对象获取对应的值对象
public Object get(Object key){
int hash = myHash(key.hashCode(), table.length);
Object value = null;
if(table[hash]!=null){
Node2 temp = table[hash];
while(temp !=null){
if(temp.key.equals(key)){
value = temp.value;
break;
}else{
temp = temp.next;
}
}
}
return value;
}
完整代码如下:
package com.jianshun;
//用于SxtHashMap中
public class Node2 {
int hash;
Object key;
Object value;
Node2 next;
}
package com.jianshun;
/**
* 自定义一个HashMap
* 增加get方法,根据对象的键对象,获取相应的值对象
* @author Administrator
*
*/
public class SxtHashMap03 {
Node2[] table; //位桶数组 bucket array
int size; //存放键值对的个数
public SxtHashMap03(){
table = new Node2[16]; // 长度一般指定为2的整数幂
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for(int i=0;i<table.length;i++){
Node2 temp = table[i];
while(temp!=null){
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
}
//根据key对象获取对应的值对象
public Object get(Object key){
int hash = myHash(key.hashCode(), table.length);
Object value = null;
if(table[hash]!=null){
Node2 temp = table[hash];
while(temp !=null){
if(temp.key.equals(key)){
value = temp.value;
break;
}else{
temp = temp.next;
}
}
}
return value;
}
//向HashMap中存储数据
public void put(Object key,Object value){
//如果要完善,还需要考虑数组扩容的问题
//定义了新的节点对象
Node2 newNode = new Node2();
newNode.hash= myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
//将链表与数组对应起来
Node2 temp = table[newNode.hash];
Node2 iterLast = null;//正在遍历的最后一个元素
boolean keyRepeat = false; // 默认不重复。
if(temp ==null){
//数组此处为空,直接将数组放进去,
table[newNode.hash] = newNode;
}else{
//此处数组元素不为空,则遍历对应链表
while(temp != null){
//判断key,如果重复则覆盖
if(temp.key.equals(key)){
keyRepeat = true;
System.out.println("key重复了");
temp.value = value; //只覆盖value即可,其他(hash,key,next) 不变.
break;
}else{
//key不重复,则遍历下一个
iterLast = temp;
temp = temp.next;
}
}
if(!keyRepeat){ // 没有发生key重复的现象,则添加到链表最后
iterLast.next = newNode;
}
}
}
public static int myHash(int v,int length){//v 为根据 key hashCode()计算出来的哈希吗
//System.out.println("hash in myHash:"+(v&(length-1)));//直接位运算,效率高
//System.out.println("hash in myHash:"+(v%(length-1)));//取模运算,效率低
return v&(length-1);
}
public static void main(String[] args) {
SxtHashMap03 m =new SxtHashMap03();
m.put(10, "aa");
m.put(20, "bb");
m.put(30, "cc");
m.put(20, "sss");
m.put(69, "abc");
System.out.println(m);
/*for(int i=0;i<100;i++){
System.out.println(i+"--"+myHash(i,16));
}*/
System.out.println(m.get(69));
}
}