Question: Hey coding peeps, I'm working on an example for CSC3 and having a really hard time implementing a comparator class. Below I've pasted the code

Hey coding peeps, I'm working on an example for CSC3 and having a really hard time implementing a comparator class. Below I've pasted the code and you'll see some commented out comparator classes I've tried to implement. This isn't graded or anything just and example I'd like to be able to do. THANKS!

package book;

import java.util.*; import java.util.ArrayList;

public class Book implements Comparable { public String author, title; public double price; // public Data releaseDate;

public Book(String author, String title, double price) { this.author = author; this.title = title; this.price = price; // this.releaseDate=releaseDate; }

public String toString() { return "Book(" + title + "," + author + ", $" + price + ")"; } public int compareTo(Book s){ return this.author.compareTo(s.author); } /* * I'd like for this to be a compartoer class which will compare the titles of books */ public int compareAuthor(Book s){ return this.title.compareTo(s.title); } /* * I'd like for this comparor class to compare the prices of book (double) */ class BookComparator2 implements Comparator { public int compare(Book s1, Book s2) { return s1.price - s2.price; } } class testBook { /** Print a List - Utility method **/ public static void printList(List L){ Iterator it=L.iterator(); while(it.hasNext()){ System.out.println(it.next()); } }

//Your Code for default comparison, // Alphabetic comparison by author //class testBook { public static void main(String[] args) { Book b1 = new Book("dad", "lorem", 7.99); Book b2 = new Book("goog", "ipsum", 2.33); Book b3 = new Book("frank", "aalor", 5.99); Book b4 = new Book("steve", "amet", 123.00); ArrayList BL=new ArrayList(); BL.add(b1); BL.add(b2); BL.add(b3); BL.add(b4); System.out.println("......Sorted according to Name......"); Collections.sort(BL); printList(BL); System.out.println(); //compareAuthor(BL); not working? } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!