Java對List停止排序的兩種完成辦法。本站提示廣大學習愛好者:(Java對List停止排序的兩種完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java對List停止排序的兩種完成辦法正文
前言
Java.util包中的List接口承繼了Collection接口,用來寄存對象集合,所以對這些對象停止排序的時分,要麼讓對象類自己完成同類對象的比擬,要麼借助比擬器停止比擬排序。
學生實體類,包括姓名和年齡屬性,比擬時先按姓名升序排序,假如姓名相反則按年齡升序排序。
第一種:實體類自己完成比擬
(完成comparable接口:public interface Comparable<T> ,外面就一個辦法聲明:public int compareTo(T o); )
示例代碼:
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
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;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
int flag = this.name.compareTo(o.name);
if(flag == 0) {
flag = this.age - o.age;
}
return flag;
}
}
然後應用List類的sort(Comparator<? super E> c)辦法或java.util.Collections工具類的sort(List<T> list) (其實外面就一句:list.sort(null); )停止排序:
List<Student> students = new ArrayList<Student>();
students.add(new Student("a",10));
students.add(new Student("b",12));
students.add(new Student("b",11));
students.add(new Student("ac",20));
students.sort(null);
//Collections.sort(students);
後果:
a 10 ac 20 b 11 b 12
第二種:借助比擬器停止排序。
示例代碼:
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
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;
}
}
比擬器java.util.Comparator類是一個接口(public interface Comparator<T> ),包括int compare(T o1, T o2);等辦法:

我們的比擬器要完成該接口並完成compare辦法:
private class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
int flag = o1.getName().compareTo(o2.getName());
if(flag == 0) {
flag = o1.getAge() - o2.getAge();
}
return flag;
}
}
比擬的時分可以應用List的sort(Comparator<? super E> c)辦法(或許java.util.Collections工具類的sort(List<T> list, Comparator<? super T> c)辦法)停止排序。
List<Student> students = new ArrayList<Student>();
students.add(new Student("a",10));
students.add(new Student("b",12));
students.add(new Student("b",11));
students.add(new Student("ac",20));
Test t = new Test();
students.sort(t.new StudentComparator());
//Collections.sort(students, t.new StudentComparator());
for(Student student : students) {
System.out.println(student.getName()+" "+student.getAge());
}
後果跟第一種辦法一樣:
a 10 ac 20 b 11 b 12
總結
以上就是關於Java中對List停止排序的全部內容了,希望本文的內容對大家的學習或許任務能帶來一定的協助,假如有疑問大家可以留言交流。