今天对HashMap做4个测试

继续使用上篇文章里手撕的DeanHashMap类做4个实验:
一、做一个测试1:
public class DeanTest1{
public static void main(String[] args){
DeanHashMap map = new DeanHashMap(10);
System.out.println(map.buckets.length);
map.put(“1”, “Absolutely”);
map.put(“2”, “Aa”);
map.put(“3”, “BB”);
map.put(“4”, “CC”);
map.put(“5”, “Bb”);
map.put(“6”,“BBBB”);
System.out.println(map.buckets.length);
}
}
/*运行结果:
10
10
二、再做一个测试2:
public class DeanTest2{
public static void main(String[] args){
DeanHashMap map = new DeanHashMap(4);
System.out.println(map.buckets.length);
map.put(“1”, “Absolutely”);
map.put(“2”, “Aa”);
map.put(“3”, “BB”);
map.put(“4”, “CC”);
map.put(“5”, “Bb”);
map.put(“6”,“BBBB”);
System.out.println(map.buckets.length);
}
}
/*运行结果:
4
8
三、再做一个测试3:
public class DeanTest3{
public static void main(String[] args){
DeanHashMap map = new DeanHashMap();
System.out.println(map.buckets.length);
map.put(“1”, “Absolutely”);
map.put(“2”, “Aa”);
map.put(“3”, “BB”);
map.put(“4”, “CC”);
map.put(“5”, “Bb”);
map.put(“6”,“BBBB”);
System.out.println(map.buckets.length);
}
}
/*运行结果:
16
16
---------- ============ ====
四、继续做一个测试4:
首先将扩容函数resize()里的 Node<K, V>[] newBuckets = new Node[buckets.length * 2];
修改成 Node<K, V>[] newBuckets = new Node[buckets.length ]; 让它没有能力扩容,然后执行下面代码:
public class DeanTest4{
public static void main(String[] args){
DeanHashMap map = new DeanHashMap(4);
System.out.println(map.buckets.length);
map.put(“1”, “Absolutely”);
map.put(“2”, “Aa”); //index=2
map.put(“3”, “BB”); //index=3
map.put(“4”, “CC”); //index=0
map.put(“5”, “Bb”); //index=1
map.put(“6”,“BBBB”);
System.out.println(map.buckets.length);

    System.out.println("Absolutely桶位:"+map.getIndex("1", 4));
    System.out.println("Aa桶位:"+map.getIndex("2", 4));
    System.out.println("BB桶位:"+map.getIndex("3", 4));
    System.out.println("CC桶位:"+map.getIndex("4", 4));
    System.out.println("Bb桶位:"+map.getIndex("5", 4));  
    System.out.println("BBBB桶位:"+map.getIndex("6", 4));

}
}
/*运行结果:
4
4
Absolutely桶位:1
Aa桶位:2
BB桶位:3
CC桶位:0
Bb桶位:1
BBBB桶位:2
我们发现1和2两个桶位形成了链表。


结论:
1、自己设定的HashMap容量就是桶数组buckets的长度;如HashMap(10), 则buckets.length=10;
2、HashMap map = new HashMap(); 默认创建一个长度为16的HashMap;
3、如果连续向HashMap添加元素的数量超过自己设定的HashMap容量,为了不发生哈希冲突(不形成链表)则会自动扩容,具体扩多少与resize()函数相关;
4、如果禁止HashMap扩容,则当加入元素的数量超过自己设定的HashMap容量,就会发生哈希冲突,进而形成链表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值