我在练习 Java 时遇到了一个问题。
我有一个 Book 类,它存储以下信息:
id (int), author and title
我还有另一个类 BookShelf,它使用 Vector/ArrayList 存储书籍集合,并具有以下方法:
addBook: takes in a book object as input, adds the object into the bookshelf, method returns nothing.
returnListOfBooks: takes in no argument and returns a Vector/ArrayList of all books sorting by title in alphabetical order.
returnListOfBooksByAuthor: takes in author as input and returns a Vector/ArrayList of books by that author
我的问题是,如何创建方法returnListOfBooks 并按书名字母顺序对它们进行排序?如果您能检查我的方法并在我做错的时候纠正我,那就太好了。
我必须实现排序(冒泡排序、插入排序等)
我是 Java 的新手,所以我不太擅长它。任何帮助将不胜感激!
最佳答案
在 Java 中,您通常使用 Collections.sort
对 List
进行排序,如果需要,还可以使用自定义比较器。 Java 8 允许使用简洁的语法。
// easy to change for descending order
Collections.sort(listOfBooks, (a, b) -> a.getTitle().compareTo(b.getTitle()));
甚至更好
Collections.sort(listOfBooks, Comparator.comparing(Book::getTitle));
请注意,两者都会对 listOfBooks
进行排序(而不是返回一个新的排序列表)。您可能不希望每次调用 returnListOfBooks
时都这样做。如果例如在 returnListOfBooksByAuthor
里面你可以
Collections.sort(listOfBooks, Comparator.comparing(Book::getAuthor));
相同的listOfBooks
这次会按照author
排序
关于java - 如何按字母顺序排序(没有 Comparable 或 Comparator 接口(interface)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546443/