Write a book class that has at least the name and price two properties. To implement the comparable interface, the CompareTo () method of the interface specifies that the size relationship of two book class instances is the size of the price property of the two. In the main function, select the appropriate collection type to hold several objects of the book class, and then create an object of the new book class and check that the object is equal to which objects in the collection.
Package Javajihe;
public class book implements comparable{
String name;
float price;
Book (String name,float Price) {
This.name=name;
This.price=price;
}
public void SetName (String name) {
This.name=name;
}
Public String GetName () {
return name;
}
public void Setprice (float price) {
This.price=price;
}
public float GetPrice () {
return price;
}
@Override
public int CompareTo (Object b) {
if ((book) b). price-this.price==0)
return 0;
if ((book) b). price-this.price!=0)
return 1;
return-1;
}
}
Package Javajihe;
Import java.util.ArrayList;
Import Java.util.Iterator;
public class Test1 {
public static void Main (string[] args) {
TODO auto-generated method stubs
arraylist<book> list = new arraylist<book> ();
Book B1=new Book ("Basic Java Tutorial", 29f);
Book B2=new Book ("Database Technology", 29f);
Book B3=new Book ("Basic C + + tutorial", 28f);
List.add (B1);
List.add (B2);
List.add (B3);
Iterator<book> it = List.iterator ();
Book Book=new Book ("Pattern Recognition", 28f);
System.out.println ("new book:" +book.name+ "with the following books:");
while (It.hasnext ())
{
Book B = It.next ();
if (Book.compareto (b) ==0)
System.out.println (B.name);
}
System.out.println ("The price is the same, the specific price is:" +book.price+ "Yuan");
}
}
Java Collection Framework Exercises: Write a book class that has at least the name and price two properties. The class to implement the comparable interface, in the interface of the CompareTo () method .....