HashMap
把Student对象作为键进行存储:
Student.java:
package com.xiaoxin.bean;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Demo4_HashMap.java:
package com.xiaoxin.map;
import com.xiaoxin.bean.Student;
import java.util.HashMap;
public class Demo4_HashMap {
//HashMap集合键是Student,值是String案例
//键是学生对象
//值是字符串对象,代表学生归属地
public static void main(String[] args) {
HashMap<Student, String> hm = new HashMap<>();
hm.put(new Student("张三", 23), "北京");
hm.put(new Student("张三", 23), "东北");
hm.put(new Student("王五", 25), "东京");
hm.put(new Student("赵六", 26), "武汉");
System.out.println(hm);
}
}
输出:
{Student [name=张三, age=23]=东北, Student [name=赵六, age=26]=武汉, Student [name=王五, age=25]=东京}
分析:
需要在Student类中重写hashCode()和equals()方法,才能在输入的时候判断Student键有没有重复
HashMap嵌套HashMap
需求:双元课堂有很多基础班,第88期基础班定义成一个双列集合,键是学生对象,值是学生的归属地
代码:
package com.xiaoxin.map;
import java.util.HashMap;
import com.xiaoxin.bean.Student;
public class Demo9_HashMapHashMap {
/*
* 双元课堂有很多基础班
* 第88期基础班定义成一个双列集合,键是学生对象,值是学生的归属地
* 第99期基础班定义成一个双列集合,键是学生对象,值是学生的归属地
*
* 无论88期还是99期,都是班级对象,为了便于统一管理,把这些班级对象添加到双元课堂集合中
*
* */
public static void main(String[] args) {
HashMap<Student, String> hm88 = new HashMap<>();
hm88.put(new Student("张三", 23), "北京");
hm88.put(new Student("张三", 23), "北京");
hm88.put(new Student("李四", 24), "武汉");
hm88.put(new Student("王五", 25), "南京");
hm88.put(new Student("赵六", 26), "上海");
HashMap<Student, String> hm99 = new HashMap<>();
hm99.put(new Student("唐僧", 23), "北京");
hm99.put(new Student("孙悟空", 24), "武汉");
hm99.put(new Student("猪八戒", 25), "南京");
hm99.put(new Student("沙和尚", 26), "上海");
HashMap<HashMap<Student, String>, String> hm = new HashMap<>();
hm.put(hm88, "第88期基础班");
hm.put(hm99, "第99期基础班");
for(HashMap<Student, String> temp : hm.keySet()) {
System.out.println(temp);
System.out.println(hm.get(temp));
}
}
}
输出:
{Student [name=张三, age=23]=北京, Student [name=李四, age=24]=武汉, Student [name=赵六, age=26]=上海, Student [name=王五, age=25]=南京}
第88期基础班
{Student [name=猪八戒, age=25]=南京, Student [name=唐僧, age=23]=北京, Student [name=沙和尚, age=26]=上海, Student [name=孙悟空, age=24]=武汉}
第99期基础班