一、Comparable接口
自定义类实现Comparable接口,在类中重写compareTo方法,如果调用对象比传入对象大则返回正数,这样排序就是升序
如图为Student类
public class Student implements Comparable{
int age;
String name;
public Student(int age) {
this.age = age;
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
@Override
public int compareTo(Object o) {
if(o instanceof Student) {
Student s = (Student) o;
return this.age - ((Student) o).age;
}else{
throw new RuntimeException("传入的数据不一致");
}
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
就可以调用Collections的sort()进行排序
public class TestStudent {
public static void main(String[] args) {
//容器
List<Student> stu = new ArrayList<>();
Student s1 = new Student(23,"ab");
Student s2 = new Student(12,"bcdef");
Student s3 = new Student(45,"cdd");
stu.add(s1);
stu.add(s2);
stu.add(s3);
Collections.sort(stu);
for(Student s:stu){
System.out.println(s);
}
}
}
输出为:
Student{age=12, name='bcdef'}
Student{age=23, name='ab'}
Student{age=45, name='cdd'}
二、Comparator接口
需要额外自定义一个类实现Comparator接口,重写compare方法,此处使用匿名实现类
Student类如图
public class Student{
int age;
String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
测试类
public class TestStudent {
public static void main(String[] args) {
//容器
List<Student> stu = new ArrayList<>();
Student s1 = new Student(23,"aaaaa");
Student s2 = new Student(12,"bb");
Student s3 = new Student(45,"cdddddddd");
stu.add(s1);
stu.add(s2);
stu.add(s3);
Comparator c = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Student && o2 instanceof Student) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.name.length()-s2.name.length();
}else{
throw new RuntimeException("传入的数据不一致");
}
}
};
Collections.sort(stu,c);
for(Student s:stu){
System.out.println(s);
}
}
}
输出为
Student{age=12, name='bb'}
Student{age=23, name='aaaaa'}
Student{age=45, name='cdddddddd'}