package October;
import java.util.Arrays;
import java.util.Comparator;
public class Common {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0]=new Book("三国演义",111);
books[1]=new Book("水浒传",222);
books[2]=new Book("西游记",333);
books[3]=new Book("红楼梦",444);
//调用Arrays.sort方法,通过接口实现排序
Arrays.sort(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//向下转型
Book i1 = (Book)o1;
Book i2 = (Book)o2;
//按照价格由小到大排序
//return (int)(i1.getPrice()-i2.getPrice());
//按照书名长度由短到长排序
return (int)(i1.getName().length()-i2.getName().length());
}
});
System.out.println(Arrays.toString(books));
}
}
class Book{
public String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "name=" + name + ",price=" + price+"\n" ;
}
}
根据价格或书名长度排序,调用接口实现
最新推荐文章于 2022-04-29 11:30:46 发布
关键词由CSDN通过智能技术生成