Java集合框架上机练习题编写一个Book类

编写一个Book类,该类至少有nameprice两个属性该类要实现Comarable接口,在接口的compareTo()方法中规定两个Book类实例的大小关系为二者的price属性的大小关系在主函数中选择合适的集合类型存放Book类的若干个对象然后创建一个新的Book类的对象,并检查该对象与集合中的哪些对象相等。查询结果如下图:


  1. import java.util.Comparator;  
  2. public class Book   implements Comparator{  
  3.     private String name;  
  4.     private int price;  
  5.     public Book(String name, int price) {  
  6.         super();  
  7.         this.name = name;  
  8.         this.price = price;  
  9.     }  
  10.       
  11.   
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.   
  16.   
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.   
  21.   
  22.     public int getPrice() {  
  23.         return price;  
  24.     }  
  25.   
  26.   
  27.     public void setPrice(int price) {  
  28.         this.price = price;  
  29.     }  
  30.   
  31.   
  32.     public Book() {  
  33.         super();  
  34.         // TODO Auto-generated constructor stub  
  35.     }  
  36.   
  37.     /*  public int compareTo(Book one, Book another) { 
  38.           int i = 0; 
  39.           i = one.name.compareTo(another.name); // 使用字符串的比较 
  40.           if(i == 0) { // 如果名字一样,比较年龄,返回比较jiage结果 
  41.                return one.price - another.price; 
  42.           } else { 
  43.                return i; // 名字不一样, 返回比较名字的结果. 
  44.           } 
  45.      }*/  
  46.     @Override  
  47.     public int compare(Object o1, Object o2) {  
  48.         // TODO Auto-generated method stub         
  49.         return ((Book)o1).price - ((Book)o2).price;   
  50.     }  
  51.   
  52. }  


  1. import java.util.ArrayList;  
  2.   
  3.   
  4. public class Demo {  
  5.   
  6.     /** 
  7.      * @param args 
  8.      */  
  9.     public static void main(String[] args) {  
  10.         // TODO Auto-generated method stub  
  11.         ArrayList  list=new ArrayList();  
  12.          list.add(new Book("java",29));  
  13.          list.add(new Book("C++",29));  
  14.          Book  book=new Book();  
  15.        int  t=   book.compare(list.get(0), list.get(1));  
  16.        if(t==0){  
  17.            System.out.println("价格相同,具体价格:"+((Book)list.get(0)).getPrice());  
  18.        }else  
  19.            System.out.println("价格不相等");  
  20.            
  21.     }  
  22.   
  23. }  
运行结果:




你可能感兴趣的:(java)