import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class hashmap_pra {
public static void main(String[] args) {
HashMap<Student,String> map1 = new HashMap<Student,String>();
map1.put(new Student("张三",23), "山东");
map1.put(new Student("李四",22), "东北");
map1.put(new Student("狐狸",24), "凯音");
HashMap<Student,String> map2 = new HashMap<Student,String>();
map2.put(new Student("hh",60), "山东");
map2.put(new Student("gg",61), "东北");
map2.put(new Student("fg",62), "凯音");
HashMap<HashMap<Student,String>,String> map =new HashMap<>();
map.put(map1, "普通版");
map.put(map2, "明星版");
//用sch来接受键值对
Set<Entry<HashMap<Student,String>,String>> sch =map.entrySet();
for (Entry<HashMap<Student,String>, String> entry : sch) {
String value= entry.getValue();//班级类型
//键值又是一个hashmap
HashMap<Student,String> banji = entry.getKey();
//用entry2来接受键值对
Set<Entry<Student,String>> entry2 = banji.entrySet();
for (Entry<Student, String> entry3 : entry2) {
System.out.println(entry3.getKey()+"籍贯为"+entry3.getValue()+"班级为"+value);
}
}
}
}
Student类:
package pra1;
public class Student implements Comparable {
private String name;
private int 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 String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
System.out.println("调用hasgcode");
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) {
System.out.println("调用equals");
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;
}
public int compareTo(Student o) {
//先按年龄排
// int num = this.age-o.age;
// return num ==0?this.name.compareTo(o.name):num;
//按照姓名
int num =this.name.compareTo(o.name);
return num==0?this.age-o.age:num;
}
@Override
public int compareTo(Object o) {
Student ol =(Student)(o);
int num = this.age-ol.age;
return num ==0?this.name.compareTo(ol.name):num;
// int num =this.name.compareTo(ol.name);
// return num==0?this.age-ol.age:num;
}
}