- HashMap存储自定义类型键值
- Map集合保证key是唯一的:作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一
package collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class Demo01HashMapSavePerson {
public static void main(String[] args) {
show01();
System.out.println("==================");
show02();
}
private static void show02() {
HashMap<Person, String> map = new HashMap<>();
map.put(new Person("女王", 18), "英国");
map.put(new Person("秦始皇", 18), "泰国");
map.put(new Person("普京", 30), "俄罗斯");
map.put(new Person("女王", 18), "毛里求斯");
Set<Map.Entry<Person, String>> set = map.entrySet();
for (Map.Entry<Person, String> entry : set) {
Person key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "-->" + value);
}
}
private static void show01() {
HashMap<String, Person> map = new HashMap<>();
map.put("北京", new Person("张三", 18));
map.put("广州", new Person("李四", 19));
map.put("广东", new Person("王五", 20));
map.put("北京", new Person("赵六", 21));
Set<String> set = map.keySet();
for (String key : set) {
Person value = map.get(key);
System.out.println(key + "-->" + value);
}
}
}
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Person person = (Person) object;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
D:\Java\jdk-17\bin\java.exe "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=13388:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\JavaSenior\out\production\Test;D:\develop\maven\repository\junit\junit\4.13.1\junit-4.13.1.jar;D:\develop\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar collection.Demo01HashMapSavePerson
广州-->Person{name='李四', age=19}
广东-->Person{name='王五', age=20}
北京-->Person{name='赵六', age=21}
==================
Person{name='女王', age=18}-->毛里求斯
Person{name='秦始皇', age=18}-->泰国
Person{name='普京', age=30}-->俄罗斯
Process finished with exit code 0
1、HashMap集合的特点