How to sort an array of objects in Java?(如何在 Java 中对对象数组进行排序?)
问题描述
我的数组不包含任何字符串.但它包含对象引用.每个对象引用都通过 toString 方法返回名称、id、作者和发布者.
My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method.
public String toString() {
return (name + "
" + id + "
" + author + "
" + publisher + "
");
}
现在我需要按名称对对象数组进行排序.我知道如何排序,但我不知道如何从对象中提取名称并对它们进行排序.
Now I need to sort that array of objects by the name. I know how to sort, but I do not know how to extract the name from the objects and sort them.
推荐答案
你有两种方法可以做到这一点,都使用 Arrays 实用类
You have two ways to do that, both use the Arrays utility class
- 实现 Comparator 并将您的数组与比较器一起传递到 sort方法将其作为第二个参数.
- 在您的对象来自的类中实现 Comparable 接口并将您的数组传递给 排序方法,只接受一个参数.
- Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
- Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
示例
class Book implements Comparable<Book> {
public String name, id, author, publisher;
public Book(String name, String id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
public String toString() {
return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
}
@Override
public int compareTo(Book o) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return toString().compareTo(o.toString());
}
}
@Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};
// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));
// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}
输出
[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]
这篇关于如何在 Java 中对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中对对象数组进行排序?
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01