gpt4 book ai didi

java - 按字母顺序对数组列表进行排序

转载 作者:行者123 更新时间:2023-12-02 06:17:38 24 4
gpt4 key购买 nike

您好,我想知道如何对这个arrayList进行排序

public class Librarian {
public static void main(String[] args){

Library library = new Library();



library.addBook(new FictionBook("The walk through the exam", "Andreas", 0));
library.addBook(new FictionBook("The incredible Programmer", "John", 1));
library.addBook(new FictionBook("The Calculator", "Pius", 1));
library.addBook(new FictionBook("The gozzilla", "Henry", 1));
library.addBook(new FictionBook("The game", "Pele", 0));
library.addBook(new FictionBook("Racing on the moon", "Marco",0));
library.addBook(new FictionBook("London Show", "William", 0));
library.addBook(new FictionBook("Water fights", "Claudia", 1));
library.addBook(new FictionBook("Monster and Dragons", "Woozer", 1));
library.addBook(new FictionBook("Pencils and pins", "Xian", 0));

for(FictionBook myFictionBook : library.library){
System.out.println(myFictionBook.getAuthor());
}
}

最佳答案

正如其他人提到的,您可以在 java 类中实现可比较接口(interface)。更好的选择是使用外部 Comparator .

Comparator<FictionBook> comparator = new Comparator<FictionBook>() {

public int compare(FictionBook a, FictionBook b) {
return a.title.compareTo(b.title);
}

}

如果您现在想根据发行年份对书籍进行排序,那么您只需实现另一个比较器并使用新的比较器即可。或者您编写一个 DecoratorComparator 来反转内部结果的结果。

逆向排序器:

Comparator<FictionBook> inverse = new Comparator<FictionBook>() {

public int compare(FictionBook a, FictionBook b) {
return comparator.compare(a, b) * -1;
}

}

实际的排序也是通过 Collections.sort(list, comparator) 完成的。如果您想要灵活的排序解决方案,请使用比较器。

关于java - 按字母顺序对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21307297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com