> 文档中心 > 【无标题】

【无标题】

Comparable & Comparator

1.需求:
【无标题】
代码:public class Test01 {
public static void main(String[] args) {
System.out.println(“按照成绩和年龄排序:”);
TreeSet set = new TreeSet();
set.add(new Student(“liusan”,20,90.0));
set.add(new Student(“lisi”,22,90.0));
set.add(new Student(“wangwu”,20,99.0));
set.add(new Student(“sunliu”,22,100.0));
for (Student student : set) {
System.out.println(student);
}

System.out.println("按照姓名排序:");TreeSet all = new TreeSet(new Comparator() {@Overridepublic int compare(Student o1, Student o2) {return o1.getName().compareTo(o2.getName());}});all.addAll(set);for (Student student : all) {System.out.println(student);}}

}