在不修改对象类的情况下实现对象数组排序,可以使用中间工具类继承Comparator接口,覆写compare()方法进行对象数组排序
以Book类对象数组为例:以下是一个Book简单类结构
class Book {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(double price) {
this.price = price;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", price=" + price +
'}';
}
}
编写中间工具类:
class BookComparator implements Comparator<Book> {
@Override
public int compare(Book o1, Book o2) {
if (o1.getPrice() > o2.getPrice()) {
return 1;
} else if (o1.getPrice() < o2.getPrice()) {
return -1;
} else {
return 0;
}
}
}
测试:使用Array.sort()方法进行排序。sort()重载方法接收两个参数,一个是要进行排序的对象数组,一个是 实现Comparator对象的工具类实例
//使用comparator排序
public class BookArray {
public static void main(String[] args) {
Book[] books=new Book[]{new Book("Java开发",309.44),
new Book("JSP开发",123.33),
new Book("Oracle开发",1233.33),
new Book("Mysql开发",23.33)
};
Arrays.sort(books,new BookComparator());
System.out.println(Arrays.toString(books));
}
}
输出结果:
[Book{title='Mysql开发', price=23.33},
Book{title='JSP开发', price=123.33},
Book{title='Java开发', price=309.44},
Book{title='Oracle开发', price=1233.33}]