Student stu1 = new Student(1, "小马", 10);
Student stu2 = new Student(2, "小马2", 10);
Student stu3 = new Student(3, "小马3", 30);
Student stu4 = new Student(4, "小马4", 40);
Student stu5 = new Student(5, "小马5", 50);
List<Student> studentList = new ArrayList<Student>();
studentList.add(stu1);
studentList.add(stu2);
studentList.add(stu3);
studentList.add(stu4);
studentList.add(stu5);
System.out.println("排序前--:" + studentList.toString());
//studentList:排序的对象
//Student:学生对象
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 从大到小(按照学生id)
//return o2.getId().compareTo(o1.getId());
// 从小到大(按照学生id)
//return o1.getId().compareTo(o2.getId());
// 从大到小(按照年龄)
return o2.getAge().compareTo(o1.getAge());
}
});
System.out.println("倒序排序后--:" + studentList.toString());
import java.util.TreeSet;
//Z类,重写了equals方法,总是返回false,
//重写了compareTo(Object obj)方法,总是返回正整数
class Z implements Comparable {
int age;
public Z(int age) {
this.age = age;
}
public boolean equals(Object obj) {
return false;
}
public int compareTo(Object obj) {
return 1;
}
}
public class TestTreeSet {
public static void main(String[] args) {
TreeSet set = new TreeSet();
Z z1 = new Z(6);
set.add(z1);
System.out.println(set.add(z1));
// 下面输出set集合,将看到有2个元素
System.out.println(set);
// 修改set集合的第一个元素的age属性
((Z) (set.first())).age = 9;
// 输出set集合的最后一个元素的age属性,将看到也变成了9
System.out.println(((Z) (set.last())).age);
}
}