🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
在不修改原本类的情况下(原本类不可能使用Comparable接口),为此java里面又出现了一个比较器: ~~~ java.util.Comparator ~~~ ~~~ @FunctionalInterface public interface Comparator<T> { public int compare(T o1, T o2); public boolean equals(Object obj); } ~~~ 而真正要实现的是compare方法,这个是要实现的排序方法 ~~~ import java.util.Arrays; import java.util.Comparator; class Book { private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } public double getPrice() { return price; } @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); sb.append("\"title\":\"") .append(title).append('\"'); sb.append(",\"price\":") .append(price); sb.append('}'); return sb.toString(); } } class BookComparator implements Comparator<Book> { @Override public int compare(Book o1, Book o2) { return (o1.getPrice() > o2.getPrice()) ? 1 : -1; } } ~~~ 而之前用Comparable接口用的是Arrays类的sort()方法,可是现在更换接口用另外一个被重置的sort方法 ~~~ public static <T> void sort(T[] a, Comparator<? super T> c); ~~~ 实现 ~~~ public static void main(String[] args) { Book[] books = new Book[]{ new Book("java开发", 80), new Book("php", 10), new Book("c++", 20) }; Arrays.sort(books, new BookComparator()); System.out.println(Arrays.toString(books)); } ~~~