/*
每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3,获取map集合中的元素。
*/
package homework;
import java.util.*;
class MapTest {
public static void main(String[] args) {
//HashMap取出方法
HashMap<Student, String> hm = new HashMap<Student, String>();
hm.put(new Student("leilaohu", 40), "dongbei");
hm.put(new Student("datufei", 55), "shandong");
hm.put(new Student("haohan", 30), "liangshan");
hm.put(new Student("dashi", 99), "yunnan");
hm.put(new Student("police", 66), "BEIJING");
hm.put(new Student("wangermazi", 66), "SIJIUCHENG");
Set<Student> KeySet = hm.keySet();
Iterator<Student> it = KeySet.iterator();
while (it.hasNext()) {
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(it.next());
}
//entrySet取出方法
Set <Map.Entry<Student, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student, String>> iter = entrySet.iterator();
while(iter.hasNext()){
Map.Entry<Student, String> en = iter.next();
Student stu = en.getKey();
String addr = en.getValue();
System.out.println("entrySet GET==="+stu+addr);
}
}
}
class Student implements Comparable<Student> {
private int age;
private String name;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int hashCode() {
return name.hashCode()+age*34;
}
public boolean equals(Object obj) {
if (!(obj instanceof Student))
throw new ClassCastException("type missing match");
Student s = (Student) obj;
return this.name.equals(s.name) && this.age == s.age;
}
public int compareTo(Student s) {
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num == 0)
return this.name.compareTo(s.name);
return num;
}
}
打印结果:
homework.Student@5af103d
homework.Student@6b20dd67
homework.Student@c56dade2
entrySet GET===homework.Student@5a47c277SIJIUCHENG
entrySet GET===homework.Student@5af103dyunnan
entrySet GET===homework.Student@560ea25ashandong
entrySet GET===homework.Student@6b20dd67dongbei
entrySet GET===homework.Student@b702f43bliangshan
entrySet GET===homework.Student@c56dade2BEIJING
和hashCode有关系么?
|
|