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 中对对象数组进行排序?
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01