Java集合框架上机练习题

Java集合框架上机练习题
1 编写一个Book类,该类至少有name和price两个属性。该类要实现Comparable接口,在接口的compareTo(

)方法中规定两个Book类实例的大小关系为二者的price属性的大小关系。在主函数中,选择合适的集合类

型存放Book类的若干个对象,然后创建一个新的Book类的对象,并检查该对象与集合中的哪些对象相等。查

询结果如下图:Java集合框架上机练习题_第1张图片

package LI;
 public class Book implements Comparable
                 // 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; 
                        } 
      
 } 
package LI;
 import java.util.*; 
 public class Test { 
     public static void main(String[] args) { 
         // TODO Auto-generated method stub  
            ArrayList list = new ArrayList();    
            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 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+"元");   
         }   
 } 

 

 

你可能感兴趣的:(Java集合框架上机练习题)