Files
javaSE-260914/s-day04/src/com/inmind/map01/MapDemo04.java
T

34 lines
1.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.inmind.map01;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/*
5.Map集合存储自定义对象
需求:每位学生(姓名,年龄)都有自己的家庭住址,我要把学生对象和居住城市存储到Map集合中,学生作为键key,居住城市作为值
注意:学生姓名和年龄如果相同看作同一个学生
哈希:通过hashCode,equals实现去重
总结:
1.hashMap存储自定义对象作为key时,要实现去重,必须在自定义类中重写hashCode,equals方法
2.HashMap:底层数据结构就是哈希表,它跟对象哈希值有关
3.HashSet 底层就是HashMap,HashMap<E,Object>,将set中的值作为map中的key,而map中值没有任何作用,就保存相同的数据
*/
public class MapDemo04 {
public static void main(String[] args) {
Map<Student, String> map = new HashMap<>();
map.put(new Student("张三1", 19), "上海");
map.put(new Student("张三2", 18), "苏州");
map.put(new Student("张三3", 21), "常州");
map.put(new Student("张三1", 19), "上海");
System.out.println(map);
HashSet<String> hashSet = new HashSet<>();
hashSet.add("");
}
}