Map体系集合
参考视频:13.33 Map集合概述哔哩哔哩bilibili
HashMap(),代码如下:
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;标签:Map,hashMap,System,treeMap,println,-----,Student,集合,out From: https://www.cnblogs.com/mokuiran/p/16600922.html
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());
}
}
}