Background information: I have a text file of books filled with their respected information (ex: title, publisher, pageCount). I have successfully created an inheritance hierarchy with all the correct implementations, get/setters, and toString methods. The inheritance hierarchy essentially looks like this (code will be provided further below):
Book
- title
- publisher
- pageCount
FictionBook inherits Book
- author
- genre
NonFictionBook inherits Book
- language
Dictionary inherits NonFictionBook
- versionNumber
CookBook inherits NonFictionBook
- topic
Novel inherits FictionBook
- isPartOfASeries (i.e. Y or N)
GraphicNovel inherits FictionBook
- illustrator
The text file looks like this:
My problem: I have been following this example: https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/ but I do not fully understand how to use the compareTo method and further accurately sort the info into the correct classes. In my current code, my compareTo method seems to be printing the whole string and not accurately sorting it. I will provide all related code, output, and the parent class for the inheritance hierarchy class for better understanding.
My Question: How do I use the compareTo and collections.sort methods to accurately sort and print out my data. I have been stuck on this for a while so any guidance to me solving and learning this is appreciated!
Book Class (The Parent Class w/ Comparator and compare method):
public abstract class Book implements Comparable {
public String title;
public String publisher;
public int pageCount;
public Book(String title, String publisher, int pageCount) {
this.title = title;
this.publisher = publisher;
this.pageCount = pageCount;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public static Comparator<Book> bookTitleComp = new Comparator<Book>() {
public int compare(Book b1, Book b2) {
String bookTitle1 = b1.getTitle().toUpperCase();
String bookTitle2 = b2.getTitle().toUpperCase();
return bookTitle1.compareTo(bookTitle2);
}
};
// @Override
public String toString() {
return "Book " "title: " title ", publisher: " publisher ", pageCount: " pageCount;
}
}
Main Class (Here I am reading in my text file, sorting by the first number in the text field, so 1 = Dictionary, 2=Cookbook, 3=Novel, 4=GraphicNovel, and trying to print my compare method: last 4 lines)
ArrayList<Book> library = new ArrayList<Book>(); //Initialize ArrayList library
//Read text file in
FileReader fr = null;
try {
fr = new FileReader("library.txt"); //Reads in text file
} catch (FileNotFoundException ex) {
Logger.getLogger(GUICommandFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader reader = new BufferedReader(fr);
try {
String line;
while((line=reader.readLine())!=null) {
System.out.println(line);
String[] splitLine = line.split(", ");
if("1".equals(splitLine[0])) {
library.add(new Dictionary(splitLine[1], splitLine[2], Integer.parseInt(splitLine[3]), splitLine[4], splitLine[5]));
} else if ("2".equals(splitLine[0])) {
library.add(new Cookbook(splitLine[1], splitLine[2], Integer.parseInt(splitLine[3]), splitLine[4], splitLine[5]));
} else if ("3".equals(splitLine[0])) {
library.add(new Novel(splitLine[1], splitLine[2], Integer.parseInt(splitLine[3]), splitLine[4], splitLine[5], splitLine[6]));
}else if ("4".equals(splitLine[0])) {
library.add(new GraphicNovel(splitLine[1], splitLine[2], Integer.parseInt(splitLine[3]), splitLine[4], splitLine[5], splitLine[6]));
}
}
} catch (IOException ex) {
Logger.getLogger(GUICommandFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Book title sorting: ");
Collections.sort(library, Book.bookTitleComp);
for(Book str: library) {
System.out.println(str);
}
Current Output:
Book title sorting:
Novel isPartOfSeries: N
Novel isPartOfSeries: N
Cookbook topic: French Cooking
GraphicNovel illustrator: Neil Gaiman
Cookbook topic: Asian Cooking
Novel isPartOfSeries: Y
Novel isPartOfSeries: Y
Cookbook topic: Keto Cooking
Novel isPartOfSeries: Y
Dictionary version number: 4
Dictionary version number: 2
GraphicNovel illustrator: Dave Gibbons
GraphicNovel illustrator: Pia Guerra
BUILD SUCCESSFUL (total time: 3 seconds)
CodePudding user response:
follow the below example
import java.util.*;
public class CustomObject {
private String customProperty;
public CustomObject(String property) {
this.customProperty = property;
}
public String getCustomProperty() {
return this.customProperty;
}
public static void main(String[] args) {
ArrayList<Customobject> list = new ArrayList<>();
list.add(new CustomObject("Z"));
list.add(new CustomObject("A"));
list.add(new CustomObject("B"));
list.add(new CustomObject("X"));
list.add(new CustomObject("Aa"));
list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty()));
for (CustomObject obj : list) {
System.out.println(obj.getCustomProperty());
}
}
}