栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

今天对HashMap做4个测试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

今天对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[] newBuckets = new Node[buckets.length * 2];
修改成 Node[] 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容量,就会发生哈希冲突,进而形成链表。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/605948.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号