排序列表<T>对象的特定规则? [英] Sort List<T> of objects by a particular rule?
问题描述
我有这个清单:
List<Country> countryList = new ArrayList<Country>();
我想通过使用方法 getCountry()
按国家名称对国家进行排序.怎样才能做到这一点?
And I want to sort the countries by their name, by using the method getCountry()
.
How can achieve this?
更新:
public class Country implements Comparable
@Override
public int compareTo(Object another) {
// TODO Auto-generated method stub
return 0;
}
你能说出如何比较它们以按字符串排序吗?阿根廷,奥地利,巴西等
Can you tell how to compare them to get it sorted by Strings? Argentina, Austria, Brazil, etc.
推荐答案
有两种方式:
让
Country
实施java.util.Comparable
接口,用于在Country
对象上定义自然排序,即创建对象本身知道"他们的顺序.然后您可以使用Collections.sort(List)
或者只是从你的List
切换到一个SortedSet
实现,比如TreeSet
> (如果你不需要重复,Set
会丢弃重复)
Have
Country
implement thejava.util.Comparable
interface to define a natural ordering on yourCountry
objects, i.e. make the objects themselves "know" their ordering. You can then useCollections.sort(List)
or just switch from yourList
to aSortedSet
implementation likeTreeSet
(if you don't need duplicates, aSet
drops duplicates)
编写一个java.util.Comparator
定义一个强制排序并调用Collections.sort(List, Comparator)
或 (再次丢失重复项)选择 new TreeSet(Comparator)
.
实现这两个中的一个就足以解决您的问题——Comparable
和 Comparator
都可以结合使用,但是:使用 Comparator
将覆盖 Comparable
定义的任何自然顺序.
Implementing one of these two is enough to solve your problem -- both Comparable
and Comparator
can be combined, though: using a Comparator
will override any natural ordering defined by Comparable
.
这篇关于排序列表<T>对象的特定规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!