import java.util.Arrays;
import java.util.Comparator;
//案例:自定义Book类,里面包含name和price,按price排序(从大到小)。要求使用两种方式排序,有一个 Book[] books = 4本书对象.
// 使用前面学习过的传递实现Comparator接口匿名内部类,也称为定制排序。[同学们完成这个即可10min ],
// 可以按照price (1)从大到小(2)从小到大(3)按照书名长度从大到小
public class ArraysExceise {
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("青年文摘20年", 5);
books[3] = new Book("java从入门到放弃~", 300);
//System.out.println(books[1]);
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
return book1.getName().length() - book2.getName().length();
// int different = book1.getPrice() - book2.getPrice();
// if(different > 0){
// return -1;
// }else if(different < 0){
// return 1;
// }else{
// return 0;
}
});
System.out.println(Arrays.toString(books));
}
}
class Book{
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private String name;
private int price;
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
ArraysExceise
最新推荐文章于 2024-09-11 00:27:03 发布