book类的设计
定义一个图书类,分别采用Comparable接口和Comparator接口两种方法使Book具有排序功能。分析主方法,将程序补充完整。
【输入形式】
【输出形式】
[(c++, cheng, 89.0), (java, zhang, 90.0), (python, wang, 92.0)]
[(c++, cheng, 89.0), (java, zhang, 90.0), (python, wang, 92.0)]
【样例输入】
【样例输出】
【样例说明】
【评分标准】
package demo1;
import java.util.Arrays;
import java.util.Comparator;
class Book implements Comparable<Book>{
private Integer price;
private String author,title;
public Book(){}
public Book(String title,String author,Integer price)
{this.title=title;
this.author=author;
this.price=price;
}
public String getTitle(){
return this.title;
}
public void setTitle(){
this.title=title;
}
public String getAuthor(){
return this.author;
}
public void setAuthor(){
this.author=author;
}
public Integer getPrice(){
return price; }
public void setPrice(Integer price){
this.price=price;
}
public String toString(){
return "("+title+", "+author+", "+(double)price+")";
}
public int compareTo(Book b) {// Comparable接口中的方法
return this.price.compareTo(b.getPrice());
}
}
class BookSortByPrice implements Comparator<Book>{
public int compare(Book o1,Book o2) {
return o1.getPrice()-o2.getPrice();
}
}
public class demo9{
public static void main(String[] args) {
Book []books=new Book[]{new Book("java","zhang",90),new Book("c++","cheng",89),new Book("python","wang",92)};
Arrays.sort(books);
System.out.println(Arrays.toString(books));
Arrays.sort(books);
Arrays.sort(books,new BookSortByPrice());
System.out.println(Arrays.toString(books));
}
}