1 编写一个Book类,该类至少有name和price两个属性。该类要实现Comarable接口,在接口的compareTo()方法中规定两个Book类实例的大小关系为二者的price属性的大小关系。在主函数中,选择合适的集合类型存放Book类的若干个对象,然后创建一个新的Book类的对象,并检查该对象与集合中的哪些对象相等。查询结果如下图:
import java.util.*;
public class Book implements Comparable<Book>{
// TODO Auto-generated method stub
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;
}
}
import java.util.*;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Book> list = new ArrayList<Book>();
Book b1=new Book("java基础教程",29f);
Book b2=new Book("数据库技术",29f);
Book b3=new Book("C++基础教程",29f);
list.add(b1);
list.add(b2);
list.add(b3);
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+"元");
}
}