Java List 對象排序是指對存儲在List中的對象進行排序??梢允褂肅ollections.sort()方法來實現,該方法需要傳入一個實現了Comparator接口的類,用于比較List中的對象。
Java List 對象排序是指對存儲在List中的對象進行排序??梢允褂肅ollections.sort()方法來實現,該方法需要傳入一個實現了Comparator接口的類,用于比較List中的對象。
是一個示例代碼:
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
public class StudentComparator implements Comparator
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
}
public class Test {
public static void main(String[] args) {
List
list.add(new Student(1, "John", 20));
list.add(new Student(2, "Bob", 18));
list.add(new Student(3, "Tom", 22));
Collections.sort(list, new StudentComparator());
for (Student student : list) {
System.out.println(student.getName() + ", " + student.getAge());
}
}
}
輸出結果:
Bob, 18
John, 20
Tom, 22
本站系公益性非盈利分享網址,本文來自用戶投稿,不代表碼文網立場,如若轉載,請注明出處
評論列表(50條)