1 编写一个Book类,该类至少有name和price两个属性。该类要实现Comparable接口,在接口的compareTo()方法中规定两个Book类实例的大小关系为二者的price属性的大小关系。在主函数中,选择合适的集合类型存放Book类的若干个对象,然后创建一个新的Book类的对象,并检查该对象与集合中的哪些对象相等。查询结果如下图:
package JAVA1;
public class Book implements Comparable<Book>{
String name;
float price;
public Book(String name,float price){
this.name=name;
this.price=price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int compareTo(Book b) {
if(b.price-this.price==0)
return 0;
if(b.price-this.price!=0)
return 1;
return -1;
}
}
package JAVA1;
import java.util.*;
public class Test {
public static void main(String[] args) {
ArrayList<Book> list = new ArrayList<Book>();
Book book1=new Book("JAVA基础教程",28f);
Book book2=new Book("数据库技术",29f);
Book book3=new Book("C++基础教程",29f);
list.add(book1);
list.add(book2);
list.add(book3);
Iterator<Book> it = list.iterator();
Book book=new Book("《模式识别》",29f);
System.out.println("新书:"+book.name+"与下列图书:");
while(it.hasNext())
{
Book b = it.next();
if(book.compareTo(b)==0)
System.out.println(b.name);
}
System.out.println("价格相同,具体价格为:"+book.price+"元");
}
}