Demo:按学生成绩进行排序
定义一个student类[code=java]package com.cast.heima;
public 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;
}
public Student(int score, int id) {
super();
this.score = score;
this.id = id;
}
@Override
public String toString() {
return "Person [score=" + score + ", id=" + id + "]";
}
}[/code]排序运行类[code=java]package com.cast.heima;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class MySort {
public static void main(String[] args) {
@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
//实例化一个TreeSet,初始化是传递一个Comparator比较器
TreeSet<Student> set = new TreeSet<Student>(new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Student p1 = (Student)o1;
Student p2 = (Student)o2;
return p1.getScore()-p2.getScore();
}
});
//实例化5个Student并对成员变量赋初始值
Student student1 = new Student(100, 1);
Student student2 = new Student(38, 2);
Student student3 = new Student(60, 3);
Student student4 = new Student(70, 4);
Student student5 = new Student(45, 5);
//把五个对象放入带比较器的set中
set.add(student1);
set.add(student2);
set.add(student3);
set.add(student4);
set.add(student5);
//使用迭代器对set集合进行迭代并打印
for(Iterator<Student> iter = set.iterator();iter.hasNext();){
System.out.println(iter.next());
}
}
}
运行结果:
Student [score=38, id=2]
Student [score=45, id=5]
Student [score=60, id=3]
Student [score=70, id=4]
Student [score=100, id=1][/code]
[ 本帖最后由 杨志罡 于 2011-07-28 20:47 编辑 ] |