我有一个对象的链接列表(书籍,其中字段是标题,作者和其他(。为什么这种按标题排序的实现会产生错误的结果?
import java.util.*;
public class sort
{
public static void main(String[] args)
{
LinkedList<Book> l = new LinkedList<>();
l.add(new Book("Vargas Fred", "Il morso della reclusa"));
l.add(new Book("Postorino Rossella", "Le assaggiatrici"));
l.add(new Book("Bythell Shaun", "Una vita da libraio"));
l.add(new Book("Simenon Georges", "Il fondo della bottiglia"));
Collections.sort(l, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.title.length() - o2.title.length();
}
});
for(Book i : l)
{
System.out.println(i.title);
}
}
}
预期: - Il fondo della bottiglia - Il morso della reclusa - 勒阿萨吉亚特里奇 - 乌纳维塔达图书馆
结果: - 勒阿萨吉亚特里奇 - 乌纳维塔达图书馆 - Il morso della reclusa - Il fondo della bottiglia
如果要按字母顺序而不是标题的长度对书籍进行排序,则需要使用以下内容:
return o1.title.compareTo(o2.title);
这应该可以解决你的问题。我正在使用 lambda 和 JDK 8
下面是一个Book
类的示例:
public class Book {
final String author;
final String title;
public Book(String author, String title) {
this.author = author;
this.title = title;
}
public String title() {
return this.title;
}
public String author() {
return this.author;
}
}
现在比较发生在这里:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortTest {
public static void main(String... args) {
List<Book> l = new ArrayList<>();
l.add(new Book("Vargas Fred", "Il morso della reclusa"));
l.add(new Book("Postorino Rossella", "Le assaggiatrici"));
l.add(new Book("Bythell Shaun", "Una vita da libraio"));
l.add(new Book("Simenon Georges", "Il fondo della bottiglia"));
Collections.sort(l, Comparator.comparing(Book::title));
l.forEach(book -> System.out.println(book.title));
}
}