package Demo_2_7_Comparable比较接口; import java.util.Arrays; public class Main { public static void main(String[] args) { Person[] data = new Person[]{ new Person("张三-A",19), new Person("李四-B",21), new Person("王五-C",12) }; Arrays.sort(data); System.out.println(Arrays.toString(data)); } } class Person implements Comparable<Person>{ private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public int compareTo(Person person) { return this.age - person.age; } @Override public String toString() { return "name: " + this.name + "\tage: " + this.age; } }
面试题:
请解释Comparable 与 Comparator的区别?
- java.lang.Comparable是在类定义的时候实现的父接口,主要用于定义排序规则,里面只有一个compareTo()方法
- java.util.Comparator是挽救的比较器操作,需要设置单独的比较器规则类实现排序,里面有compare()方法