请把学生名与考试分数录入到Map中,并按分数显示前三名成绩学员的名字。
@Test
public void test2() {
Comparator com
= new Comparator() {
public int compare(Object o1, Object o2) {
if (o1 instanceof Student
&& o2 instanceof Student) {
Student s1
= (Student) o1;
Student s2
= (Student) o2;
if (s1
.getScore()
!= s2
.getScore()) {
return s1
.getScore()
- s2
.getScore();
}
else{
return s1
.getId()
-s2.getId();
}
}
return 0;
}
};
Map map = new TreeMap(com);
map.put(
new Student(
001,
87),
"吴将1");
map.put(
new Student(
002,
87),
"吴将2");
map.put(
new Student(
004,
96),
"吴将3");
map.put(
new Student(
003,
75),
"吴将4");
Set entry
= map.entrySet();
List list=new ArrayList(entry);
Collections
.reverse(
list);
for(int i
=0;i
<3;i
++){
System
.out
.println(
list.get(i));
}
}
}
接上面,学生类
public class Student {
private int id;
private int score;
public Student() {
super();
}
public Student(
int id,
int score) {
super();
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public void setId(
int id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(
int score) {
this.score = score;
}
@Override
public String
toString() {
return "Student [id=" + id +
", score=" + score +
"]";
}
@Override
public int hashCode() {
final int prime =
31;
int result =
1;
result = prime * result + id;
result = prime * result + score;
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 (id != other.id)
return false;
if (score != other.score)
return false;
return true;
}
}