public class Arrays02 {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0] = new Book("红楼梦", 100);
books[1] = new Book("金瓶梅", 90);
books[2] = new Book("青年文摘", 5);
books[3] = new Book("Java从入门到放弃", 300);
// 按照price来排序
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
// 判断转换
Book k1 = (Book) o1;
Book k2 = (Book) o2;
double ret = k1.price - k2.price;
if (ret > 0) {
return -1;
} else {
return 1;
}
}
});
// 按照书名来排序
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
// 判断转换
Book k1 = (Book) o1;
Book k2 = (Book) o2;
return k1.name.compareTo(k2.name);
}
});
for (Book book : books) {
System.out.println(book);
}
}
}
class Book {
public String name;
public double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}