如何从 ArrayList 中排序 Objects

How to Sort Objects from ArrayList

背景信息: 我有一个书籍的文本文件,里面填满了他们的相关信息(例如:书名、出版商、页数)。我已经成功地创建了一个具有所有正确实现、get/setters 和 toString 方法的继承层次结构。继承层次结构基本上是这样的(代码将在下面进一步提供):

本书

FictionBook 继承 Book

NonFictionBook 继承 Book

Dictionary 继承 NonFictionBook

CookBook 继承 NonFictionBook

小说继承FictionBook

GraphicNovel 继承 FictionBook

文本文件如下所示:

我的问题: 我一直在关注这个例子:https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/ 但我不完全理解如何使用 compareTo 方法并进一步准确地将信息排序到正确 classes。在我当前的代码中,我的 compareTo 方法似乎在打印整个字符串,但没有准确地对其进行排序。我将提供所有相关代码、输出和继承层次结构 class 的 parent class 以便更好地理解。

我的问题:如何使用 compareTo 和 collections.sort 方法准确排序和打印我的数据。我已经坚持了一段时间,所以对我解决和学习这个问题的任何指导表示赞赏!

Book Class(Parent Class w/ Comparator 和比较方法):

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(这里我正在阅读我的文本文件,按文本字段中的第一个数字排序,所以 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)

按照下面的例子

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());
        }
    }
}