当对自己定义的数据结构需要进行指定排序的时候,java中给了我们两个接口Comparable和Comparator
第一种:实现Comparator<T>接口
public class test { public static void main(String[] args){ String[] arr = {"aaa","bbbb","c","dd"}; Arrays.sort(arr,new LengthCompartor()); System.out.println(Arrays.toString(arr)); } } class LengthCompartor implements Comparator<String> { @Override public int compare(String first, String second) { return first.length() - second.length(); } }
第二种:
public class test { public static void main(String[] args){ String[] arr = {"aaa","bbbb","c","dd"}; Arrays.sort(arr, new Comparator<String>() { @Override public int compare(String first, String second) { return first.length() - second.length(); } }); System.out.println(Arrays.toString(arr)); } }
第三种:要排序的类实现Comparable<T>接口
public class test { public static void main(String[] args){ ArrayList<Employee> list = new ArrayList<>(); list.add(new Employee(1,1000)); list.add(new Employee(2,500)); list.add(new Employee(3,800)); list.add(new Employee(4,700)); list.add(new Employee(5,1500)); Collections.sort(list); System.out.println(list); } } class Employee implements Comparable<Employee>{ int salary; int id; public Employee(int id,int salary){ this.id = id; this.salary = salary; } @Override public int compareTo(Employee o) { return this.salary - o.salary; } @Override public String toString() { return "Employee{" + "salary=" + salary + ", id=" + id + '}'; } }
在设计初时有需求就选择Comparable,若后期需要扩展或增加排序需求时,再增加一个比较器Comparator。