Avatar ·

Java中按字段对ArrayList自定义对象进行排序

大家好!我是Java新手,在排序对象列表时遇到了问题。我有一个`Book`类,包含`title`(String)和`year`(int)字段。我将几本书存储在`ArrayList`中,现在需要按出版年份对这个列表进行排序——从最旧到最新。 我听说过`Collections.sort()`,但它只适用于数字或字符串列表。当我尝试将其应用于我的书籍列表时,编译器报错:"The method sort(List) in the type Collections is not applicable for the arguments (ArrayList)"。 以下是我的示例代码: ```java import java.util.ArrayList; import java.util.Collections; public class Book { String title; int year; public Book(String title, int year) { this.title = title; this.year = year; } public static void main(String[] args) { ArrayList books = new ArrayList<>(); books.add(new Book("战争与和平", 1869)); books.add(new Book("1984", 1949));