簡體   English   中英

如何對 ArrayList 中的對象進行排序

[英]How to Sort Objects from ArrayList

背景信息:我有一個文本文件,其中包含書籍的相關信息(例如:書名、出版商、頁數)。 我已經成功創建了一個 inheritance 層次結構,其中包含所有正確的實現、get/setter 和 toString 方法。 inheritance 層次結構基本上如下所示(代碼將在下面進一步提供):

  • 標題
  • 出版商
  • 頁數

FictionBook 繼承 Book

  • 作者
  • 類型

NonFictionBook 繼承 Book

  • 語言

Dictionary 繼承 NonFictionBook

  • 版本號

CookBook 繼承 NonFictionBook

  • 話題

小說繼承 FictionBook

  • isPartOfASeries(即 Y 或 N)

GraphicNovel 繼承 FictionBook

  • 插畫師

文本文件如下所示:

文本文件

我的問題:我一直在關注這個例子: https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/但我不完全理解如何使用compareTo 方法,並進一步准確地將信息分類到正確的類中。 在我當前的代碼中,我的 compareTo 方法似乎在打印整個字符串,但沒有准確地對其進行排序。 我將提供所有相關代碼,output,以及 inheritance 層次結構 class 的父級 class,以便更好地理解。

我的問題:如何使用 compareTo 和 collections.sort 方法准確排序和打印我的數據。 我已經堅持了一段時間,所以對我解決和學習這個問題的任何指導表示贊賞!

圖書 Class(帶比較器和比較方法的父 Class):

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

當前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)

按照下面的例子

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM