# java对对象排序

public class Student {

private String name;

private int age;

public Student() {}

public Student(String name, int age) {
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;
}
}

1、通过类实现Comparable<T>接口进行排序

public class Student implements Comparable<Student>{

private String name;

private int age;

public Student() {}

public Student(String name, int age) {
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;
}

/**
* 将对象按姓名字典序升序排序
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Client {

public static void main(String[] args){
List<Student> students = new ArrayList<>();

Collections.sort(students);
for(Student student:students){
System.out.println(student.toString());
}
}

}

Student{name='a', age=18}
Student{name='b', age=20}
Student{name='c', age=19}

2、通过在Collections.sort()方法中实现Comparable<T>接口来实现排序

/**
* 没有实现Comparable<T>接口的学生类
*/
public class Student{

private String name;

private int age;

public Student() {}

public Student(String name, int age) {
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 String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Client {

public static void main(String[] args){
List<Student> students = new ArrayList<>();

Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1);
}
});
for(Student student:students){
System.out.println(student.toString());
}
}

}

Student{name='b', age=20}
Student{name='c', age=19}
Student{name='a', age=18}

posted @ 2018-04-20 11:42  ColdCode  阅读(19116)  评论(3编辑  收藏  举报