背景資訊:我有一個包含書籍的文本檔案,其中包含其受人尊敬的資訊(例如:標題、出版商、pageCount)。我已經成功地創建了一個具有所有正確實作、get/setter 和 toString 方法的繼承層次結構。繼承層次結構本質上是這樣的(代碼將在下面進一步提供):
書
- 標題
- 出版商
- 頁數
FictionBook 繼承 Book
- 作者
- 型別
NonFictionBook 繼承 Book
- 語言
Dictionary 繼承 NonFictionBook
- 版本號
CookBook 繼承 NonFictionBook
- 話題
小說繼承小說
- isPartOfASeries(即 Y 或 N)
GraphicNovel 繼承 FictionBook
- 插畫家
文本檔案如下所示:

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;
}
}
主類(這里我正在閱讀我的文本檔案,按文本欄位中的第一個數字排序,所以 1 = Dictionary、2=Cookbook、3=Novel、4=GraphicNovel,并嘗試列印我的比較方法:最后 4 行)
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);
}
電流輸出:
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)
uj5u.com熱心網友回復:
按照下面的例子
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());
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426652.html
