比如,某个List中存储了Student类的对象,比较简单的,我们要对List中的Student类的对象按照他们的年龄排序(升序、降序均有可能)。Collections.sort()方法可以对Integer、String等已经实现Comparable接口的类直接进行排序,但是Student类是原生的,如果直接硬生生的使用Collections.sort(testList)方法,估计就会按照对象的存储地址直接排序了。很明显,这不是我们想要的结果。其次,Collections.sort()方法默认是升序排序的,而现实需求中,降序排序也是很大概率出现的需求。主要的实现方法有两种:
(1)Student类实现Comparable接口,重写CompareTo()方法,实现如下:
class Student{ //Comparable<Student>
private String studentName;//学生姓名
private int age;//学生年龄
private String sex;
public Student(String studentName,int age,String sex){
this.studentName = studentName;
this.age = age;
this.sex = sex;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
//重写compareTo方法
@Override
public int compareTo(Student student) {
if(this.age<student.age){
return -1;
//这样是直接调用了 可以直接自己实现 按照自己的方法来实现
}
if(this.age>student.age){
return 1;
}
return 0;
}
}
这样之后,比如我们在main()方法里边实例化几个Student类的对象,然后直接调用Collections.sort(testList);其中,testList用于存储Student类的对象,代码粘贴如下:
public static void main(String[] args) {
List<Student> testList = new ArrayList<Student>();
//实例化Student对象
Student student2 = new Student("Test1",18,"FM");
Student student3 = new Student("Test2",19,"M");
Student student4 = new Student("Test3",20,"FM");
Student student1 = new Student("Roland",17,"M");
//数据构造完成
testList.add(student1);
testList.add(student2);
testList.add(student3);
testList.add(student4);
Collections.sort(testList);
//foreach循环打印输出
for(Student student:testList){
System.out.println(student.getStudentName()+"-->"+student.getAge());
}
}
通过观察循环输出,我们可以发现是按照升序输出的,如果要实现降序输出,只需要将Student类中的CompareTo()方法中的返回值都取反即可。
(2)Student类不实现Comparable接口,而是在调用Collections.sort()方法时,new Comparator<Student>()对象出来,实现升序或者降序操作,Student类中只需要简单的属性和set、get方法。代码粘贴如下:
public static void main(String[] args) {
List<Student> testList = new ArrayList<Student>();
Student student2 = new Student("Test1",18,"FM");
Student student3 = new Student("Test2",19,"M");
Student student4 = new Student("Test3",20,"FM");
Student student1 = new Student("Roland",17,"M");
//数据构造完成
testList.add(student1);
testList.add(student2);
testList.add(student3);
testList.add(student4);
Collections.sort(testList,new Comparator<Student>(){
public int compare(Student student1,Student student2){
if(student1.getAge()<student2.getAge()){
return 1;
}
if(student1.getAge() == student2.getAge()){
return 0;
}
return -1;
}
});//默认是是升序
//foreach循环打印输出
for(Student student:testList){
System.out.println(student.getStudentName()+"-->"+student.getAge());
}
}
我们可以看到,按照上边的代码,打印到控制台的输出是降序的,当然如果要改为升序,只需要将上述的compare()方法中的返回值取反即可。动手实现验证了下,记录下来,加深印象,方便以后使用。