**问题:(本例中)Collections.sort方法是用来排序的 吗? 如果是 那下面的compare方法是干什么的啊
还是需要 Collections.sort 和 compare方法 结合才能实现排序 **。以学的就没有Collections.sort这个方法啊,??
各位, 请看 代码
public class StudentDesc implements Comparable<StudentDesc> {
private String name;
private Integer age;
public StudentDesc(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
public int compareTo(StudentDesc o) {
if(null == this.age) {
return 1;
}
if(null == o.getAge()) {
return -1;
}
return o.age.compareTo(this.getAge());
}
@Override
public String toString() {
return "StudentDesc{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//升序排序
Student studentWang = new Student("王小二", 10);
Student studentZhang = new Student("张三", 1);
Student studentGou = new Student("狗子", 99);
Student studentZhao = new Student("赵六", 40);
Student studentLi = new Student("李四", null);
List<Student> students = new ArrayList<Student>(Arrays.asList(studentWang, studentZhang, studentGou, studentZhao, studentLi));
//sort方法是用来排序的 吗? 如果是 那下面的compare方法是干什么的啊
//还是需要 sort 和 compare方法 结合才能实现排序
Collections.sort(students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
if(null == o1.getAge()) {
return -1;
}
if(null == o2.getAge()) {
return 1;
}
return o1.getAge().compareTo(o2.getAge());
}
});
System.out.println("自定义对象,升序排序:");
for(Student student : students) {
System.out.println(student.toString());
}