I am new to java I have a class with 4 attributes , based on which i need to sort my object . I could achieve sorting upto three level ie on Author , title and price , can any one help me to extend it to publisher.
My code : Sorts object based on Author Name first , if Same Author Name it sorts on title , if same title it sorts on price .
Now i want if same price , sort on publisher . Can any one help me with this ?
Here is the code :
//Book.java
public class Book implements Comparable<Book>{
String title;
String author;
double price;
String publisher;
//getters and setters for 4 variables
public int compareTo(Book book){
if(book == null){
throw new NullPointerException("Book passed is null!");
}
if(this.getAuthor().equals(book.getAuthor())){ /*Most significant field*/
if(this.getTitle().equals(book.getTitle())) /*Next Most significant field*/
return (int)(this.getPrice()-book.getPrice());
else
return this.getTitle().compareTo(book.getTitle());
}
else
return this.getAuthor().compareTo(book.getAuthor());
}
}
//BookComparison.java
import java.util.Arrays;
public class BookComparision{
public static void main(String args[]){
Book book1 = new Book();
book1.setAuthor("Author A");
book1.setTitle("Title B");
book1.setPrice(225.00);
Book book2 = new Book();
book2.setAuthor("Author A");
book2.setTitle("Title B");
book2.setPrice(125.00);
Book book3 = new Book();
book3.setAuthor("Author B");
book3.setTitle("Title B");
book3.setPrice(125.00);
Book book4 = new Book();
book4.setAuthor("Author B");
book4.setTitle("Title A");
book4.setPrice(200.00);
Book book5 = new Book();
book5.setAuthor("Author C");
book5.setTitle("Title C");
book5.setPrice(125.00);
Book book6 = new Book();
book6.setAuthor("Author C");
book6.setTitle("Title B");
book6.setPrice(125.00);
Book book7 = new Book();
book7.setAuthor("Author C");
book7.setTitle("Title B");
book7.setPrice(400.00);
/* An array containing Books*/
Book[] bookArray = new Book[7];
bookArray[0]=book1;
bookArray[1]=book2;
bookArray[2]=book3;
bookArray[3]=book4;
bookArray[4]=book5;
bookArray[5]=book6;
bookArray[6]=book7;
System.out.println("Sorted Books:");
Arrays.sort(bookArray);
for(int i=0;i<=6;i++){
System.out.print("Author:"+bookArray[i].getAuthor()+" ");
System.out.print("Title:"+bookArray[i].getTitle()+" ");
System.out.println("Price:"+bookArray[i].getPrice());
}
}
}
Thanks in Advance Manas