java.util.Collections.sort(List<T> list)方法的声明
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
java.util.Collections.sort(List<T> list,Comparator<? super T> c
)方法的声明
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
(1)如果是单一的数据存放在集合中,是可以直接排序的
private static void sort1() {
List list = new ArrayList();
list.add(9);
list.add(29);
list.add(100);
list.add(3);
// sort(集合)
Collections.sort(list);
for (Object object : list) {
System.out.println(object);
}
}
(2)如果是对象数据存放在集合中,是不可以直接排序的!
(a)实体类必须要实现这个接口Comparable
/**
* 实体类 必须实现这个接口Comparable
*
* @author Administrator
*
*/
public class Student implements Comparable<Student> {
// 属性
private String name;
private int age;
private String sex;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
/**
* 带参数的构造方法
*
* @param name
* @param age
* @param sex
*/
public Student(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
/**
* 无参的构造方法
*/
public Student() {
super();
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
/**
* 重写比较方法
* 按照此比较的东西从小到大排列
*/
@Override
public int compareTo(Student o) {
if (this.age < o.age)
return -1;
if (this.age > o.age) {
return 1;
}
return 0;
}
}
测试类:
private static void sort2() {
// 1实例化对象
Student stu1 = new Student("qq", 22, "F");
Student stu2 = new Student("rose", 16, "M");
Student stu3 = new Student("boy", 25, "F");
Student stu4 = new Student("fei", 18, "M");
List<Student> list1 = new ArrayList<Student>();
list1.add(stu1);
list1.add(stu2);
list1.add(stu3);
list1.add(stu4);
// Exception in thread "main" java.lang.ClassCastException:
// com.hlx.Student cannot be cast to java.lang.Comparable
Collections.sort(list1);
for (Student student : list1) {
System.out.println(student);
}
}
效果: 从小到大的顺序排序
(b)用Comparator接口
注意:实体类不需要实现这个接口
测试类:
private static void mysort1() {
// 1实例化对象
Student stu1 = new Student("qq", 22, "F");
Student stu2 = new Student("rose", 16, "M");
Student stu3 = new Student("boy", 25, "F");
Student stu4 = new Student("fei", 18, "M");
List<Student> list1 = new ArrayList<Student>();
list1.add(stu1);
list1.add(stu2);
list1.add(stu3);
list1.add(stu4);
// 这样就可以实现自定义降序或者升序排列list了
Collections.sort(list1, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() > o2.getAge()) {
return -1;
} else if (o1.getAge() < o2.getAge()) {
return 1;
}
return 0;
}
});
for (Student student : list1) {
System.out.println(student);
}
}
效果: 从大到小的顺序排序