2022年03月27日讲到了 Map集合,同志们
1. 如何遍历 Map集合
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String,String> hashMap=new HashMap<>();
hashMap.put("101","灶神");
hashMap.put("102","关二爷");
hashMap.put("103","梁红玉");
hashMap.put("104","貔貅");
// 遍历 Map集合有两种方法
// 第一种方法: 获取 Map集合的 Set集合
Set<String> keySet = hashMap.keySet();
// 创建 Set集合的迭代器
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()){
// 迭代器读取到的是 key值
String key = iterator.next();
// 根据 key值拿 value值
String value = hashMap.get(key);
System.out.println(key+"--"+value);
}
System.out.println("=================================");
// 第二种方法: 通过 加强for 循环遍历 Map集合
Set<Map.Entry<String, String>> entries = hashMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey(); //得到 key值
String value = entry.getValue(); //得到 value值
System.out.println(key+"--"+value);
}
}
}
不要用变量当 key值,同志们
2. 题目
给你一个学生名单, 用 Map集合 把学生保存起来
学生信息用对象保存, 相同年级的学生放在一起
最后打印出来
李四 男 法学专业 211
王五 男 材料工程 212
小白 女 运管专业 211
public class test {
public static void main(String[] args) throws FileNotFoundException {
// String(班级)当 key值 List<Student>(学生)当 value值 创建 Map集合
Map<String, List<Student>> map = new HashMap<>();
Set<Map.Entry<String, List<Student>>> entries = map.entrySet();
//用 Scanner 扫描 file文件夹下的 student文本文件, 里面是学生名单
Scanner scanner = new Scanner(new File("file/student.txt"));
//扫描文件中的内容
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//小白,女,运管专业,211
//赵六,男,弹药工程,212
//信息都是用","隔开的
String[] message = line.split(",");
Student student = new Student(message[0], message[1], message[2], message[3]);
List<Student> list = new ArrayList();
list.add(student);
// 如果 Map集合里没有这个年级
if (map.get(student.getGrade()) == null) {
// 就把 student 加入Map集合
map.put(student.getGrade(), list);
} else { // 如果 Map集合里有这个年级
// 加入对应的 List集合
map.get(student.getGrade()).add(student);
}
}
//最后输出一下
for (Map.Entry<String, List<Student>> entry : entries) {
String key = entry.getKey();
List<Student> value = entry.getValue();
System.out.println(key + "----------" + value);
}
}
}
3. Set集合
也是一个集合,但里面不能有相同元素
同时加入好多个 "123",里面只存了 一个
并且保存的时候顺序是乱的
HashSet<String> hashSet=new HashSet<>(); //创建 HashSet集合
下面就是一些理论上的东西了:
HashSet集合 通过 equals()方法判断对象是否相等
存进去一个元素时, HashSet会调用 hashCode()方法得到 元素的哈希值
哈希值可以决定 元素 存储在集合中的位置
两个元素 equals() 返回 true, 哈希值不同
这是不可能的
两个元素 equals() 返回 true, 哈希值相同
只能添加一个
两个元素 equals() 返回 false, 哈希值相同
这是有可能的
System.out.println("重地".hashCode()); System.out.println("通话".hashCode()); // 这两个词儿的哈希值都是 1179395
他们还是可以加到 HashSet集合中的
这就是哈希冲突
哈希值相同的 不同对象 都存储在链表里
但如果 哈希值相同的 元素太多 查找速度就变慢了
JDK1.8以后就加了个叫红黑树的东西
元素数量超过8个 就把链表换成红黑树
THE END (= ̄ω ̄=)