手动实现HashMap3_重写toString()打印Map的内容,hashmap3tostring
分享于 点击 48346 次 点评:100
手动实现HashMap3_重写toString()打印Map的内容,hashmap3tostring
package com.jianshun;
//用于SxtHashMap中
public class Node2 {
int hash;
Object key;
Object value;
Node2 next;
}
package com.jianshun;
/**
* 自定义一个HashMap
* 重写toString方法,方便我们查看HashMap的键值对信息
* @author Administrator
*
*/
public class SxtHashMap02 {
Node2[] table; //位桶数组 bucket array
int size; //存放键值对的个数
public SxtHashMap02(){
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();
}
//向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) {
SxtHashMap02 m =new SxtHashMap02();
m.put(10, "aa");
m.put(20, "bb");
m.put(30, "cc");
m.put(20, "sss");
System.out.println(m);
/*for(int i=0;i<100;i++){
System.out.println(i+"--"+myHash(i,16));
}*/
}
}
相关文章
- 暂无相关文章
用户点评