使用Collections.sort()方法进行实现:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Child {
private int id;
private String name;
public Child() {
super();
}
public Child(int id, String name) {
super();
this.id = id;
this.name = name;
}
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 static void main(String[] args) {
List<Child> list = new ArrayList<Child>();
Child child1 = new Child(1,"aa");
Child child2 = new Child(2,"bb");
Child child3 = new Child(3,"cc");
Child child4 = new Child(4,"dd");
list.add(child1);
list.add(child2);
list.add(child3);
list.add(child4);
//对链表进行排序
Collections.sort(list, new sortById());
System.out.println("按照id进行排序:");
for (Child child : list) {
System.out.println(child.getId()+" "+child.getName());
}
}
}
//实现Comparator接口
class sortById implements Comparator{
public int compare(Object o1, Object o2) {
if(((Child)o1).getId()>((Child)o2).getId())
return 1;
return -1;
}
}