如何排序在Java中对象的数组? [英] 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 + "\n" + id + "\n" + author + "\n" + publisher + "\n");
}
现在我需要排序的名称数组对象。我知道如何排序,但我不知道如何从这些对象中提取的名称和排序。
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.
推荐答案
您有两种方式来做到这一点,无论使用的阵列实用工具类
You have two ways to do that, both use the Arrays utility class
- 实施一个比较并通过你与比较的<一个沿阵列href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28T%5B%5D,%20java.util.Comparator%29\"相对=nofollow>其中把它作为第二个参数排序的方法。
- 实施在可比接口类你的对象距离,并通过阵列的<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28java.lang.Object%5B%5D%29\"相对=nofollow>排序方法其中仅采用一个参数。
- 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中对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文