集合框架5-----Map体系
参考视频:
import java.util.HashMap;
import java.util.Map;
public class HashDemo2 {
public static void main(String[] args) {
//创建集合
HashMap<Object, Object> hashMap = new HashMap<>();
//1.添加元素
Student s1 = new Student("小明",11);
Student s2 = new Student("小红",12);
Student s3 = new Student("小李",13);
hashMap.put(s1,"北京");
hashMap.put(s2,"天津");
hashMap.put(s3,"上海");
hashMap.put(new Student("小李",13),"上海");//由于重写了hashcode和equals方法,所以不会添加进去
/*如果将上行代码,也就是小李的地址改为南京,则最终输出是南京,相当于修改了小李的地址*/
System.out.println(hashMap.toString());/*输出{Student{name='小明', age=11}=北京, Student{name='小李',
age=13}=上海, Student{name='小红', age=12}=天津}*/
//2.删除略
// hashMap.remove(s3);
// System.out.println(hashMap.size());//输出2
//3.遍历
//3.1使用keySet()方法
for (Object key:hashMap.keySet()) {
System.out.println(key.toString()+":"+hashMap.get(key));
}
System.out.println("------------------------------------------");
//3.2使用entrySet()方法
for (Map.Entry<Object,Object> entry:hashMap.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//4.判断
System.out.println(hashMap.containsKey(s1));
System.out.println(hashMap.containsValue("上海"));
System.out.println(hashMap.isEmpty());
}
}
import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Student,String> treeMap = new TreeMap<>();
//1.添加元素
Student s1 = new Student("小明",11);
Student s2 = new Student("小红",12);
Student s3 = new Student("小李",13);
treeMap.put(s1,"南京");
treeMap.put(s2,"上海");
treeMap.put(s3,"湖南");
treeMap.put(new Student("小红",18),"天津");
System.out.println(treeMap.size());//输出需要实现Comparable接口
//2.删除
// 1. treeMap.remove(s3);
// 2. treeMap.remove(new Student("小红"),18);
//3.遍历
//3.1使用keySet()
for (Student s: treeMap.keySet()) {
System.out.println(s+":"+treeMap.get(s));
}
System.out.println("------------------------------");
for (Map.Entry<Student,String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~