import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TestCollections1{
public static void main(String[] args) {
public int compare(Object o1, Object o2) {//对比必须写全了,否则由于set为无序,不可重复集合,易导致丢失元素。
if (o1 instanceof Student && o2 instanceof Student) {
Student e1=(Student)o1;
Student e2=(Student)o2;
int i=e1.getScore()-(e2.getScore());
if(i==0){
return e1.getId()-(e2.getId());
}return i;
}
return 0;
}
};
Map map =new TreeMap(com);
map.put(new Student(99, 001), "小米");
map.put(new Student(69, 003), "红米");
map.put(new Student(79, 006), "大米");
map.put(new Student(89, 005), "咪咪");
//通过entrySet方法把Map类型转化为Set集合。
Set entry=map.entrySet();
//把Set集合转化为List集合
List list =new ArrayList(entry);
Collections.reverse(list);
System.out.println("前三名姓名为:");
for (int i = 0; i < 3; i++) {
System.out.println(list.get(i));
}
}
}
class Student{
private int score;
private int id;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@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;
}
public Student(int score, int id) {
super();
this.score = score;
this.id = id;
}
@Override
public String toString() {
return "Student [score=" + score + ", id=" + id + "]";
}
}