排序列表&LT; T&GT;通过特定规则的对象? [英] 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.
推荐答案
有两种方式:
-
的
国家
实施的java.util.Comparable
接口定义的自然顺序在国家
对象,即让对象本身知道自己的排序。然后,您可以使用<一个href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29\"相对=nofollow>Collections.sort(名单)
或从你的列表只需切换
来一的SortedSet
实施如TreeSet的
(如果你不需要重复,一个设置
滴重复)
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
来定义的订货实行并调用<一个href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"相对=nofollow> Collections.sort(列表,比较器)
或(再次失去两份)走了新TreeSet的(比较)
。
实现这两个中的一个,就足以解决你的问题 - 无论是可比
和比较
可自由组合,虽然:使用比较
将覆盖定义的任何自然顺序可比
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
.
这篇关于排序列表&LT; T&GT;通过特定规则的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!