目标:
使用HashMap存储自定义对象;
自定义Person类,将Person类对象作为HashMap集合的键或值存储;
作为键存储时候需要重写该类的hashCode()和equals()方法;
Person
类:
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person that = (Person) o;
return age == that.age &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "["+getName() +","+getAge() +"]";
}
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;
}
}
HashMap
集合使用:
public class Demo02HashMapDiyObj {
public static void main(String[] args) {
show01();
}
private static void show01() {
/*
使用HashMap存储自定义对象;Person类;
*/
HashMap< String, Person> map = new HashMap<>() ;
map.put("北京",new Person("迪丽热巴",22) );
map.put("上海",new Person("古力娜扎",21) );
map.put("郑州",new Person("玛玛哈哈",23) );
//遍历输出map(键值对)
Set<Map.Entry<String, Person>> entries = map.entrySet();
for(Map.Entry<String, Person> entry :entries ){
System.out.println(entry.getKey() +"---"+entry.getValue());
}
System.out.println("-----------------");
HashMap<Person,String> map1 = new HashMap<>();
map1.put(new Person("迪丽热巴",18),"北京");
map1.put(new Person("古力娜扎",18),"郑州");
map1.put(new Person("玛玛哈哈",18),"杭州");
map1.put(new Person("迪丽热巴",18),"上海");
//遍历输出map1(键值对)
Set<Map.Entry<Person, String>> entries1 = map1.entrySet();
for(Map.Entry<Person,String> entry1:entries1 ){
System.out.println(entry1.getKey() +"---"+entry1.getValue());
}
}
}
程序运行结果: