我們需要對類別按照類別中的某一個屬性(或多個屬性)來對類別的物件進行排序,有兩種方法可以實現,一種方法是類別實現Comparable8742468051c85b06f0a0af9e3e506b5c
接口,然後呼叫Collections.sort(List)
方法進行排序,另一種方法是類別不實作Comparable8742468051c85b06f0a0af9e3e506b5c
接口,而在排序時使用Collections.sort(List, Comparator8742468051c85b06f0a0af9e3e506b5c)
方法,並實作其中的Comparator8742468051c85b06f0a0af9e3e506b5c介面。
免費學習影片教學推薦:java影片教學
先建立一個簡單的學生類別:
public class Student { private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1、透過類別實作Comparable 2、透過在Collections.sort()方法中實作Comparable8742468051c85b06f0a0af9e3e506b5c介面來實作排序 相關文章教學推薦:java程式入門 以上是java中實作對類別的物件進行排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* 将对象按姓名字典序升序排序
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Client {
public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("a", 18));
students.add(new Student("c", 19));
students.add(new Student("b", 20));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1);
}
});
for(Student student:students){
System.out.println(student.toString());
}
}
}