Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

AWS Certified Database Study Guide Specialty DBS-C01 Exam

Authors: Matheus Arrais, Rene Martinez Bravet, Leonardo Ciccone, Angie Nobre Cocharero, Erika Kurauchi, Hugo Rozestraten

1st Edition

1119778956, 978-1119778950

More Books

Students also viewed these Databases questions