-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapTest.java
More file actions
78 lines (63 loc) · 1.79 KB
/
MapTest.java
File metadata and controls
78 lines (63 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Created by fengqiang on 2017/4/25.
*/
/*
每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3,获取map集合中的元素。
*/
import java.util.*;
class Student implements Comparable<Student>{
private int age;
private String name;
Student(String name, int age){
this.age = age;
this.name = name;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+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;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name) && this.age==s.age;
}
}
class MapTest {
public static void main(String[] args){
HashMap<Student, String> hm = new HashMap<Student, String>();
hm.put(new Student("feng", 20),"beijing");
hm.put(new Student("lisi1",21),"beijing1");
hm.put(new Student("lisi1",21),"beijing2");
hm.put(new Student("lisi3",21),"beijing3");
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(stu+"======"+addr);
}
}
}