Phase 3: Add to the generic implementation completed in Phase 2 to include the e
ID: 3878947 • Letter: P
Question
Phase 3: Add to the generic implementation completed in Phase 2 to include the extra operations of getting a sorted list of library books (based on 2 different orderings) and getting a list of overdue library books. This phase will add to the class LibraryGeneric(see below).
This phase will give you practice using the Java Comparator interface and function objects.
Adding features to the LibraryGeneric class
Notice that the provided code includes a method for sorting an ArrayList of items. Both the type of items in the ArrayList and the order of the sort is generic. The ordering is specified by the Comparator object passed to the method.
Feature 1: retrieving a list of library books sorted by ISBN. This feature has been implemented for you. The getInventoryList method first makes a copy of the list of library books and then invokes the sort method with an instance of the OrderByIsbn class (a Comparator function object).
Feature 2: retrieving a list of library books sorted by author. This is similar to Feature 1, except you must provide the code for the OrderByAuthorcomparator (for which the class declaration is provided, you must fill in the code), and you must fill in the getOrderedByAuthormethod. You do not need to sort by last name, just sort by the full author String as is. If two books have the same author, this Comparator should break the tie with the book title. For example, Mushroom_Publishing.txt contains the following two books:
Moyra Caldecott The Eye of Callanish
Moyra Caldecott Crystal Legends
The OrderByAuthor comparator should treat "Crystal Legends" as less than "The Eye of Callanish", even though they have the same author, but since 'C' is alphabetically less than 'T'. To perform these comparisons, simply use String's built-in compareTo method. Then invoke the sort method with an instance of OrderByAuthor.
Feature 3: retrieving a list of overdue library books sorted by due date (oldest first). This feature is left for you to implement. In getOverdueList, first make a copy of the list of library books, but include only those that are overdue (note that GregorianCalendar has a compareTo method for comparing dates). Then invoke the sort method on the overdue list with an instance of the OrderByDueDate class (a Comparator), for which the class declaration is provided, but you must fill in the rest of the implementation.
Be sure to test these features by adding to the LibraryGenericTest or creating a new test class!
this is the code you need to add to the LibraryGeneric class
/**
* Returns the list of library books, sorted by ISBN (smallest ISBN first).
*/
public ArrayList<LibraryBookGeneric<Type>> getInventoryList() {
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByIsbn comparator = new OrderByIsbn();
sort(libraryCopy, comparator);
return libraryCopy;
}
/**
* Returns the list of library books, sorted by author
*/
public ArrayList<LibraryBookGeneric<Type>> getOrderedByAuthor() {
// FILL IN -- do not return null
return null;
}
/**
* Returns the list of library books whose due date is older than the input
* date. The list is sorted by date (oldest first).
*
* If no library books are overdue, returns an empty list.
*/
public ArrayList<LibraryBookGeneric<Type>> getOverdueList(int month, int day,
int year) {
// FILL IN -- do not return null
return null;
}
/**
* Performs a SELECTION SORT on the input ArrayList.
* 1. Find the smallest item in the list.
* 2. Swap the smallest item with the first item in the list.
* 3. Now let the list be the remaining unsorted portion
* (second item to Nth item) and repeat steps 1, 2, and 3.
*/
private static <ListType> void sort(ArrayList<ListType> list,
Comparator<ListType> c) {
for (int i = 0; i < list.size() - 1; i++) {
int j, minIndex;
for (j = i + 1, minIndex = i; j < list.size(); j++)
if (c.compare(list.get(j), list.get(minIndex)) < 0)
minIndex = j;
ListType temp = list.get(i);
list.set(i, list.get(minIndex));
list.set(minIndex, temp);
}
}
/**
* Comparator that defines an ordering among library books using the ISBN.
*/
protected class OrderByIsbn implements Comparator<LibraryBookGeneric<Type>> {
/**
* Returns a negative value if lhs is smaller than rhs. Returns a positive
* value if lhs is larger than rhs. Returns 0 if lhs and rhs are equal.
*/
public int compare(LibraryBookGeneric<Type> lhs,
LibraryBookGeneric<Type> rhs) {
return (int) (lhs.getIsbn() - rhs.getIsbn());
}
}
/**
* Comparator that defines an ordering among library books using the author, and book title as a tie-breaker.
*/
protected class OrderByAuthor implements
Comparator<LibraryBookGeneric<Type>> {
// FILL IN
}
/**
* Comparator that defines an ordering among library books using the due date.
*/
protected class OrderByDueDate implements Comparator<LibraryBookGeneric<Type>> {
// FILL IN
}
and this is the LibraryGeneric
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class LibraryGeneric<Type> {
private ArrayList<LibraryBookGeneric<Type>> library;
public LibraryGeneric() {
library = new ArrayList<LibraryBookGeneric<Type>>();
}
/**
* Add the specified book to the library, assume no duplicates.
*
*/
public void add(long isbn, String author, String title) {
library.add(new LibraryBookGeneric<Type>(isbn, author, title));
}
/**
* Add the list of library books to the library, assume no duplicates.
*/
public void addAll(ArrayList<LibraryBookGeneric<Type>> list) {
library.addAll(list);
}
/**
* Add books specified by the input file. One book per line with ISBN,
* author, and title separated by tabs.
*/
public void addAll(String filename) {
ArrayList<LibraryBookGeneric<Type>> toBeAdded = new ArrayList<LibraryBookGeneric<Type>>();
try (Scanner fileIn = new Scanner(new File(filename))) {
int lineNum = 1;
while (fileIn.hasNextLine()) {
String line = fileIn.nextLine();
try (Scanner lineIn = new Scanner(line)) {
lineIn.useDelimiter("\t");
if (!lineIn.hasNextLong()) {
throw new ParseException("ISBN", lineNum);
}
long isbn = lineIn.nextLong();
if (!lineIn.hasNext()) {
throw new ParseException("Author", lineNum);
}
String author = lineIn.next();
if (!lineIn.hasNext()) {
throw new ParseException("Title", lineNum);
}
String title = lineIn.next();
toBeAdded.add(new LibraryBookGeneric<Type>(isbn, author, title));
}
lineNum++;
}
} catch (FileNotFoundException e) {
System.err.println(e.getMessage() + " Nothing added to the library.");
return;
} catch (ParseException e) {
System.err.println(e.getLocalizedMessage() + " formatted incorrectly at line " + e.getErrorOffset()
+ ". Nothing added to the library.");
return;
}
library.addAll(toBeAdded);
}
/**
* Returns the holder of the library book with the specified ISBN.
*
*/
public Type lookup(long isbn) {
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
return library.get(i).getHolder();
}
}
return null;
}
public ArrayList<LibraryBookGeneric<Type>> lookup(Type holder) {
ArrayList<LibraryBookGeneric<Type>> foundBooks = new ArrayList<LibraryBookGeneric<Type>>();
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getHolder() == holder) {
foundBooks.add(library.get(i));
}
}
return foundBooks;
}
public LibraryBookGeneric<Type> getBook(long isbn) {
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
return library.get(i);
}
}
return null;
}
public boolean checkout(long isbn, Type holder, int month, int day, int year) {
// FILL IN -- do not return false unless appropriate
GregorianCalendar dueDate = new GregorianCalendar(year, month, day);
if (lookup(isbn) == null) {
LibraryBookGeneric<Type> currentBook = getBook(isbn);
if (currentBook != null) {
currentBook.setDueDate(dueDate);
currentBook.setHolder(holder);
return true;
}
return false; // no book found
}
return false; // book already checked out
}
public boolean checkin(long isbn) {
// FILL IN -- do not return false unless appropriate
LibraryBookGeneric<Type> check = getBook(isbn);
if (check != null) {
if (lookup(isbn) != null) {
check.setDueDate(null);
check.setHolder(null);
return true;
}
return false; // Book checked in already
}
return false; // no book found
}
public boolean checkin(Type holder) {
ArrayList<LibraryBookGeneric<Type>> current = new ArrayList<LibraryBookGeneric<Type>>();
current = lookup(holder);
if (current.isEmpty()) {
return false;
}
for (LibraryBookGeneric<Type> book : current) {
book.setDueDate(null);
book.setHolder(null);
}
return true;
}
/**
* Returns the list of library books, sorted by ISBN (smallest ISBN first).
*/
public ArrayList<LibraryBookGeneric<Type>> getInventoryList() {
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByIsbn comparator = new OrderByIsbn();
sort(libraryCopy, comparator);
return libraryCopy;
}
public ArrayList<LibraryBookGeneric<Type>> getOverdueList(int month, int day, int year) {
Calendar overDue = new GregorianCalendar(year, month, day);
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByDueDate comparator = new OrderByDueDate();
// First remove books that do not have a DueDate (not checked
// out)
for (int i = libraryCopy.size() - 1; i >= 0; i--) {
if (libraryCopy.get(i).getDueDate() == null) {
libraryCopy.remove(i);
}
}
for (int i = libraryCopy.size() - 1; i >= 0; i--) {
Calendar bookDue = libraryCopy.get(i).getDueDate();
if (overDue.compareTo(bookDue) <= 0) {
libraryCopy.remove(i);
}
}
sort(libraryCopy, comparator);
return libraryCopy;
}
/**
* Returns the list of library books, sorted by author
*/
public ArrayList<LibraryBookGeneric<Type>> getOrderedByAuthor() {
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByAuthors comparator = new OrderByAuthors();
sort(libraryCopy, comparator);
return libraryCopy;
}
private static <ListType> void sort(ArrayList<ListType> list, Comparator<ListType> c) {
for (int i = 0; i < list.size() - 1; i++) {
int j, minIndex;
for (j = i + 1, minIndex = i; j < list.size(); j++)
if (c.compare(list.get(j), list.get(minIndex)) < 0)
minIndex = j;
ListType temp = list.get(i);
list.set(i, list.get(minIndex));
list.set(minIndex, temp);
}
}
/**
* Comparator that defines an ordering among library books using the ISBN.
*/
protected class OrderByIsbn implements Comparator<LibraryBookGeneric<Type>> {
/**
* Returns a negative value if lhs is smaller than rhs. Returns a
* positive value if lhs is larger than rhs. Returns 0 if lhs and rhs
* are equal.
*/
public int compare(LibraryBookGeneric<Type> lhs, LibraryBookGeneric<Type> rhs) {
return lhs.getIsbn() > rhs.getIsbn() ? 1 : (lhs.getIsbn() < rhs.getIsbn() ? -1 : 0);
}
}
/**
* Comparator that defines an ordering among library books using the due
* date.
*/
protected class OrderByDueDate implements Comparator<LibraryBookGeneric<Type>> {
public int compare(LibraryBookGeneric<Type> lhs, LibraryBookGeneric<Type> rhs) {
return lhs.getDueDate().compareTo(rhs.getDueDate());
}
}
/**
* Comparator that defines an ordering among library books using the author,
* and book title as a tie-breaker.
*/
protected class OrderByAuthors implements Comparator<LibraryBookGeneric<Type>> {
public int compare(LibraryBookGeneric<Type> lhs, LibraryBookGeneric<Type> rhs) {
return lhs.getAuthor().compareToIgnoreCase(rhs.getAuthor());
}
}
}
LIBRARY BOOK GENERIC CLASS
import java.util.GregorianCalendar;
public class LibraryBookGeneric<Type> extends Book {
private Type holder;
private GregorianCalendar dueDate;
public LibraryBookGeneric(long isbn, String author, String title) {
super(isbn, author, title);
this.holder = null;
this.dueDate = null;
}
/**
* @return the author
*/
public Type getHolder() {
return this.holder;
}
/**
* @return the due date of a book
*/
public GregorianCalendar getDueDate() {
return this.dueDate;
}
/**
* sets the holder of the book
*/
public void setHolder(Type holder) {
this.holder = holder;
}
/**
* sets the due date of the book
*/
public void setDueDate(GregorianCalendar dueDate) {
this.dueDate = dueDate;
}
}
Explanation / Answer
//LibraryGenericTest.java
import java.util.ArrayList;
import java.util.GregorianCalendar;
public class LibraryGenericTest {
public static void main(String[] args) {
// test a library that uses names (String) to id patrons
LibraryGeneric<String> lib1 = new LibraryGeneric<String>();
lib1.add(9780374292799L, "Thomas L. Friedman", "The World is Flat");
lib1.add(9780330351690L, "Jon Krakauer", "Into the Wild");
lib1.add(9780446580342L, "David Baldacci", "Simple Genius");
String patron1 = "Jane Doe";
if (!lib1.checkout(9780330351690L, patron1, 1, 1, 2008))
System.err.println("TEST FAILED: first checkout");
if (!lib1.checkout(9780374292799L, patron1, 1, 1, 2008))
System.err.println("TEST FAILED: second checkout");
ArrayList<LibraryBookGeneric<String>> booksCheckedOut1 = lib1
.lookup(patron1);
if (booksCheckedOut1 == null
|| booksCheckedOut1.size() != 2
|| !booksCheckedOut1.contains(new Book(9780330351690L, "Jon Krakauer",
"Into the Wild"))
|| !booksCheckedOut1.contains(new Book(9780374292799L,
"Thomas L. Friedman", "The World is Flat"))
|| !booksCheckedOut1.get(0).getHolder().equals(patron1)
|| !booksCheckedOut1.get(0).getDueDate().equals(
new GregorianCalendar(2008, 1, 1))
|| !booksCheckedOut1.get(1).getHolder().equals(patron1)
|| !booksCheckedOut1.get(1).getDueDate().equals(
new GregorianCalendar(2008, 1, 1)))
System.err.println("TEST FAILED: lookup(holder)");
if (!lib1.checkin(patron1))
System.err.println("TEST FAILED: checkin(holder)");
// test a library that uses phone numbers (PhoneNumber) to id patrons
LibraryGeneric<PhoneNumber> lib2 = new LibraryGeneric<PhoneNumber>();
lib2.add(9780374292799L, "Thomas L. Friedman", "The World is Flat");
lib2.add(9780330351690L, "Jon Krakauer", "Into the Wild");
lib2.add(9780446580342L, "David Baldacci", "Simple Genius");
PhoneNumber patron2 = new PhoneNumber("801.555.1234");
if (!lib2.checkout(9780330351690L, patron2, 1, 1, 2008))
System.err.println("TEST FAILED: first checkout");
if (!lib2.checkout(9780374292799L, patron2, 1, 1, 2008))
System.err.println("TEST FAILED: second checkout");
ArrayList<LibraryBookGeneric<PhoneNumber>> booksCheckedOut2 = lib2.lookup(patron2);
if (booksCheckedOut2 == null
|| booksCheckedOut2.size() != 2
|| !booksCheckedOut2.contains(new Book(9780330351690L, "Jon Krakauer",
"Into the Wild"))
|| !booksCheckedOut2.contains(new Book(9780374292799L,
"Thomas L. Friedman", "The World is Flat"))
|| !booksCheckedOut2.get(0).getHolder().equals(patron2)
|| !booksCheckedOut2.get(0).getDueDate().equals(
new GregorianCalendar(2008, 1, 1))
|| !booksCheckedOut2.get(1).getHolder().equals(patron2)
|| !booksCheckedOut2.get(1).getDueDate().equals(
new GregorianCalendar(2008, 1, 1)))
System.err.println("TEST FAILED: lookup(holder)");
if (!lib2.checkin(patron2))
System.err.println("TEST FAILED: checkin(holder)");
System.out.println("Testing done.");
}
}
=============================================================================
//LibraryTest.java
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Random;
public class LibraryTest {
public static void main(String[] args) {
// test an empty library
Library lib = new Library();
if (lib.lookup(978037429279L) != null)
System.err.println("TEST FAILED -- empty library: lookup(isbn)");
ArrayList<LibraryBook> booksCheckedOut = lib.lookup("Jane Doe");
if (booksCheckedOut == null || booksCheckedOut.size() != 0)
System.err.println("TEST FAILED -- empty library: lookup(holder)");
if (lib.checkout(978037429279L, "Jane Doe", 1, 1, 2008))
System.err.println("TEST FAILED -- empty library: checkout");
if (lib.checkin(978037429279L))
System.err.println("TEST FAILED -- empty library: checkin(isbn)");
if (lib.checkin("Jane Doe"))
System.err.println("TEST FAILED -- empty library: checkin(holder)");
// test a small library
lib.add(9780374292799L, "Thomas L. Friedman", "The World is Flat");
lib.add(9780330351690L, "Jon Krakauer", "Into the Wild");
lib.add(9780446580342L, "David Baldacci", "Simple Genius");
if (lib.lookup(9780330351690L) != null)
System.err.println("TEST FAILED -- small library: lookup(isbn)");
if (!lib.checkout(9780330351690L, "Jane Doe", 1, 1, 2008))
System.err.println("TEST FAILED -- small library: checkout");
booksCheckedOut = lib.lookup("Jane Doe");
if (booksCheckedOut == null
|| booksCheckedOut.size() != 1
|| !booksCheckedOut.get(0).equals(
new Book(9780330351690L, "Jon Krakauer", "Into the Wild"))
|| !booksCheckedOut.get(0).getHolder().equals("Jane Doe")
|| !booksCheckedOut.get(0).getDueDate().equals(
new GregorianCalendar(2008, 1, 1)))
// System.out.println(booksCheckedOut.get(0).getDueDate().toString());
System.err.println("TEST FAILED -- small library: lookup(holder)");
if (!lib.checkin(9780330351690L))
System.err.println("TEST FAILED -- small library: checkin(isbn)");
if (lib.checkin("Jane Doe"))
System.err.println("TEST FAILED -- small library: checkin(holder)");
// test a medium library
lib.addAll("" + "" +
"Mushroom_Publishing.txt");
// FILL IN
System.out.println("Testing done.");
}
public static ArrayList<LibraryBook> generateLibrary(int size) {
ArrayList<LibraryBook> result = new ArrayList<LibraryBook>();
for (int i = 0; i < size; i++) {
// generate random ISBN
Random randomNumGen = new Random();
String isbn = "";
for (int j = 0; j < 13; j++)
isbn += randomNumGen.nextInt(10);
result.add(new LibraryBook(Long.parseLong(isbn), "An author", "A title"));
}
return result;
}
public static long generateIsbn() {
Random randomNumGen = new Random();
String isbn = "";
for (int j = 0; j < 13; j++)
isbn += randomNumGen.nextInt(10);
return Long.parseLong(isbn);
}
}
=====================================================================================
//PhoneNumber.java
public class PhoneNumber {
private String areaCode;
private String trunk;
private String rest;
public PhoneNumber(String phoneNum) {
phoneNum = phoneNum.replaceAll("-|\s|\.|\(|\)", "");
boolean isValid = true;
if (phoneNum.length() != 10)
isValid = false;
for (int i = 0; isValid && i < 10; i++)
if (!Character.isDigit(phoneNum.charAt(i)))
isValid = false;
if (isValid) {
areaCode = phoneNum.substring(0, 3);
trunk = phoneNum.substring(3, 6);
rest = phoneNum.substring(6, 10);
} else {
areaCode = "000";
trunk = "000";
rest = "000";
System.err.println("Phone number "" + phoneNum
+ "" is not formatted correctly, initializing as " + toString()
+ ".");
}
}
public boolean equals(Object other) {
if (!(other instanceof PhoneNumber))
return false;
PhoneNumber rhs = (PhoneNumber) other;
PhoneNumber lhs = this;
return lhs.areaCode.equals(rhs.areaCode) && lhs.trunk.equals(rhs.trunk)
&& lhs.rest.equals(rhs.rest);
}
public String toString() {
return "(" + areaCode + ") " + trunk + "-" + rest;
}
}
==============================================================================
// LibraryGeneric.java
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;
public class LibraryGeneric<Type> {
private ArrayList<LibraryBookGeneric<Type>> library;
public LibraryGeneric() {
library = new ArrayList<LibraryBookGeneric<Type>>();
}
public void add(long isbn, String author, String title) {
library.add(new LibraryBookGeneric<Type>(isbn, author, title));
}
public void addAll(ArrayList<LibraryBookGeneric<Type>> list) {
library.addAll(list);
}
@SuppressWarnings("resource")
public void addAll(String filename) {
ArrayList<LibraryBookGeneric<Type>> toBeAdded = new ArrayList<LibraryBookGeneric<Type>>();
try {
Scanner fileIn = new Scanner(new File(filename));
int lineNum = 1;
while (fileIn.hasNextLine()) {
String line = fileIn.nextLine();
Scanner lineIn = new Scanner(line);
lineIn.useDelimiter("\t");
if (!lineIn.hasNextLong())
throw new ParseException("ISBN", lineNum);
long isbn = lineIn.nextLong();
if (!lineIn.hasNext())
throw new ParseException("Author", lineNum);
String author = lineIn.next();
if (!lineIn.hasNext())
throw new ParseException("Title", lineNum);
String title = lineIn.next();
toBeAdded.add(new LibraryBookGeneric(isbn, author, title));
lineNum++;
}
} catch (FileNotFoundException e) {
System.err.println(e.getMessage()
+ " Nothing added to the library.");
return;
} catch (ParseException e) {
System.err.println(e.getLocalizedMessage()
+ " formatted incorrectly at line " + e.getErrorOffset()
+ ". Nothing added to the library.");
return;
}
library.addAll(toBeAdded);
}
public Type lookup(long isbn) {
// FILL IN -- do not return null unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
return library.get(i).getHolder();
}
}
return null;
}
public ArrayList<LibraryBookGeneric<Type>> lookup(Type holder) {
// FILL IN -- do not return null
ArrayList<LibraryBookGeneric<Type>> holderBooks = new ArrayList<LibraryBookGeneric<Type>>();
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getHolder() == holder) {
holderBooks.add(library.get(i));
}
}
return holderBooks;
}
public boolean checkout(long isbn, Type holder, int month, int day, int year) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
library.get(i).holder = holder;
library.get(i).setDueDate(month, day, year);
return true;
}
}
return false;
}
public boolean checkin(long isbn) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
library.get(i).checkIn(isbn);
return true;
}
}
return false;
}
public boolean checkin(Type holder) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getHolder() == holder) {
library.get(i).checkIn(holder);
return true;
}
}
return false;
}
public ArrayList<LibraryBookGeneric<Type>> getInventoryList() {
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByIsbn comparator = new OrderByIsbn();
sort(libraryCopy, comparator);
return libraryCopy;
}
public ArrayList<LibraryBookGeneric<Type>> getOrderedByAuthor() {
// FILL IN -- do not return null
ArrayList<LibraryBookGeneric<Type>> libraryCopy = new ArrayList<LibraryBookGeneric<Type>>();
libraryCopy.addAll(library);
OrderByAuthor comparator = new OrderByAuthor();
sort(libraryCopy, comparator);
return libraryCopy;
}
public ArrayList<LibraryBookGeneric<Type>> getOverdueList(int month, int day,
int year) {
// FILL IN -- do not return null
return null;
}
private static <ListType> void sort(ArrayList<ListType> list,
Comparator<ListType> c) {
for (int i = 0; i < list.size() - 1; i++) {
int j, minIndex;
for (j = i + 1, minIndex = i; j < list.size(); j++)
if (c.compare(list.get(j), list.get(minIndex)) < 0)
minIndex = j;
ListType temp = list.get(i);
list.set(i, list.get(minIndex));
list.set(minIndex, temp);
}
}
protected class OrderByIsbn implements Comparator<LibraryBookGeneric<Type>> {
public int compare(LibraryBookGeneric<Type> lhs,
LibraryBookGeneric<Type> rhs) {
return (int) (lhs.getIsbn() - rhs.getIsbn());
}
}
protected class OrderByAuthor implements Comparator<LibraryBookGeneric<Type>> {
public int compare(LibraryBookGeneric<Type> lhs, LibraryBookGeneric<Type> rhs) {
return (int) (lhs.getAuthor().compareTo(rhs.getAuthor()));
}
}
/**
* Comparator that defines an ordering among library books using the due date.
*/
protected class OrderByDueDate implements Comparator<LibraryBookGeneric<Type>> {
public int compare(LibraryBookGeneric<Type> lhs, LibraryBookGeneric<Type> rhs) {
return (int) (lhs.getDueDate().compareTo(rhs.getDueDate()));
}
}
}
==============================================================================
//LibraryBookGeneric.java
import java.util.GregorianCalendar;
public class LibraryBookGeneric<Type> extends Book {
Type holder;
private GregorianCalendar dueDate;
public LibraryBookGeneric(long isbn, String author, String title) {
super(isbn, author, title);
}
public Type getHolder() {
return holder;
}
public void setDueDate(int month, int day, int year){
dueDate = new GregorianCalendar(year, month, day);
}
public GregorianCalendar getDueDate() {
return dueDate;
}
public void checkOut(long isbn, Type bookHolder) {
holder = bookHolder;
}
public void checkIn(long isbn) {
holder = null;
dueDate = null;
}
public void checkIn(Type bookHolder) {
holder = null;
dueDate = null;
}
}
==================================================================================
import java.util.GregorianCalendar;
public class LibraryBook extends Book {
String holder;
private GregorianCalendar dueDate;
int month;
int day;
int year;
public LibraryBook(long isbn, String author, String title) {
super(isbn, author, title);
}
public String getHolder() {
return holder;
}
public void setDueDate(int month, int day, int year) {
dueDate = new GregorianCalendar(year, month, day);
}
// If getter is sued, the dueDate is returned.
public GregorianCalendar getDueDate() {
return dueDate;
}
// The holder variable for the object is set to the bookHolder name imported.
public void checkOut(long isbn, String bookHolder) {
holder = bookHolder;
}
// The holder and the dueDate are set to null for use with isbn.
public void checkIn(long isbn) {
holder = null;
dueDate = null;
}
public void checkIn(String bookHolder) {
holder = null;
dueDate = null;
}
}
=================================================================================
//Library.java
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Library {
private ArrayList<LibraryBook> library;
public Library() {
library = new ArrayList<LibraryBook>();
}
public void add(long isbn, String author, String title) {
library.add(new LibraryBook(isbn, author, title));
}
public void addAll(ArrayList<LibraryBook> list) {
library.addAll(list);
}
public void addAll(String filename) {
ArrayList<LibraryBook> toBeAdded = new ArrayList<LibraryBook>();
try {
Scanner fileIn = new Scanner(new File(filename));
int lineNum = 1;
while (fileIn.hasNextLine()) {
String line = fileIn.nextLine();
Scanner lineIn = new Scanner(line);
lineIn.useDelimiter("\t");
if (!lineIn.hasNextLong())
throw new ParseException("ISBN", lineNum);
long isbn = lineIn.nextLong();
if (!lineIn.hasNext())
throw new ParseException("Author", lineNum);
String author = lineIn.next();
if (!lineIn.hasNext())
throw new ParseException("Title", lineNum);
String title = lineIn.next();
toBeAdded.add(new LibraryBook(isbn, author, title));
lineNum++;
}
} catch (FileNotFoundException e) {
System.err.println(e.getMessage()
+ " Nothing added to the library.");
return;
} catch (ParseException e) {
System.err.println(e.getLocalizedMessage()
+ " formatted incorrectly at line " + e.getErrorOffset()
+ ". Nothing added to the library.");
return;
}
library.addAll(toBeAdded);
}
public String lookup(long isbn) {
// FILL IN -- do not return null unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
return library.get(i).getHolder();
}
}
return null;
}
public ArrayList<LibraryBook> lookup(String holder) {
// FILL IN -- do not return null
ArrayList<LibraryBook> holderBooks = new ArrayList<LibraryBook>();
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getHolder() == holder) {
holderBooks.add(library.get(i));
}
}
return holderBooks;
}
public boolean checkout(long isbn, String holder, int month, int day, int year) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
library.get(i).holder = holder;
library.get(i).setDueDate(month, day, year);
return true;
}
}
return false;
}
public boolean checkin(long isbn) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getIsbn() == isbn) {
library.get(i).checkIn(isbn);
return true;
}
}
return false;
}
public boolean checkin(String holder) {
// FILL IN -- do not return false unless appropriate
for (int i = 0; i < library.size(); i++) {
if (library.get(i).getHolder() == holder) {
library.get(i).checkIn(holder);
return true;
}
}
return false;
}
}
================================================================================
//Book.java
public class Book {
private long isbn;
private String author;
private String title;
public Book(long _isbn, String _author, String _title) {
this.isbn = _isbn;
this.author = _author;
this.title = _title;
}
public String getAuthor() {
return this.author;
}
public long getIsbn() {
return this.isbn;
}
public String getTitle() {
return this.title;
}
public boolean equals(Object other) {
Book otherBook = null;
if(other instanceof Book)
otherBook = (Book) other;
else
return false;
if (this.isbn == otherBook.isbn &&
this.author == otherBook.author &&
this.title == otherBook.title)
return true;
else
return false;
}
/**
* Returns a string representation of the book.
*/
public String toString() {
return isbn + ", " + author + ", "" + title + """;
}
}
================================================================================
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.