您的位置:首页 > 其它

List集合实现自定义排序

2016-12-06 14:55 465 查看
List自定义排序根据Collections.sort重载方法来实现,实现Comparable接口。

实现Comparator
,重写compare方法。

public class DataSort implements Comparator<Student>{

/**
* 重写方法 实现自定义排序
*/
@Override
public int compare(Student o1, Student o2) {
int i = o1.getAge() - o2.getAge();//按照年龄排序(从小到大)
//年龄相等的情况下
if(i == 0){
return 0;
}
return i;
}

public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
students.add(new Student(11));
students.add(new Student(21));
students.add(new Student(31));
students.add(new Student(22));
students.add(new Student(15));
students.add(new Student(27));
for(Student stu : students) {
System.out.println("age:" + stu.getAge());
}
Collections.sort(students,new DataSort());  //排序
for(Student stu : students) {
System.out.println("age:" + stu.getAge());
}
}
}


student类:

public class Student {

private int age;

public Student(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: