package edu.wtbu;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Demo01 {
public static void main(String[] args) {
//HashMap集合的使用:存储结构:哈希表(数组+链表+红黑树)
//使用key的hashCode和equals作为重复
//HashMap:线程不安全,运行效率快,允许null作为key或是value
/*
源码分析:
1 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 HashMap初始容量大小
2 static final int MAXIMUM_CAPACITY = 1 << 30; HashMap的数组最大容量
3 static final float DEFAULT_LOAD_FACTOR = 0.75f; 默认加载因子
4 static final int TREEIFY_THRESHOLD = 8; jdk1.8 当链表长度大于8时,调整为红黑树
5 static final int UNTREEIFY_THRESHOLD = 6; jdk1.8 当链表长度小于6时,调整为链表
6 static final int MIN_TREEIFY_CAPACITY = 64; jdk1.8 当链表长度大于8,并且数组元素个数大于等于64时,会调整为红黑树
7 transient Node<K,V>[] table; 哈希表中的数组
8 size 元素个数
*/
/*
无参构造:
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
*/
/*
put方法:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
*/
/*
总结:
1.HashMap刚创建时,table是null,为了节省空间;当添加第一个元素时,table容量调整为16
2.当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的两倍,目的是减少调整元素的个数,提高效率
3.jdk1.8 当链表长度大于8,并且数组元素个数大于等于64时,会调整为红黑树,目的提高执行效率
4.jdk1.8 当链表长度小于6时,调整为链表
5.jdk1.8以前,链表是头插入,jdk1.8以后是尾插入
*/
//创建集合
HashMap<Student, String> hashMap = new HashMap<>();
//1.添加元素
Student s1 = new Student("张三", 16);
Student s2 = new Student("李四", 17);
Student s3 = new Student("王五", 18);
hashMap.put(s1,"湖北");
hashMap.put(s2,"湖南");
hashMap.put(s3,"深圳");
//hashMap.put(s3,"上海");
hashMap.put(new Student("王五", 18),"深圳");
System.out.println("元素个数:"+hashMap.size());//元素个数:3
System.out.println(hashMap);//{Student{name='王五', stuNo=18}=深圳, Student{name='张三', stuNo=16}=湖北, Student{name='李四', stuNo=17}=湖南}
//2.删除元素
hashMap.remove(s1);
System.out.println("元素个数:"+hashMap.size());//元素个数:2
System.out.println(hashMap);//{Student{name='王五', stuNo=18}=深圳, Student{name='李四', stuNo=17}=湖南}
//3.遍历
//1.使用KeySet
Set<Student> keySet = hashMap.keySet();
for (Student key:
keySet) {
System.out.println(key+"--------"+hashMap.get(key));
}
//2.使用EntrySet
Set<Map.Entry<Student, String>> entrySet = hashMap.entrySet();
for (Map.Entry<Student, String> entry:
entrySet) {
//System.out.println(entry.getKey()+"-----------"+entry.getValue());
System.out.println(entry);
}
//4.判断
System.out.println(hashMap.containsKey(s2));//true
System.out.println(hashMap.isEmpty());//false
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!