排序列表<T>对象的特定规则? [英] Sort List&lt;T&gt; of objects by a particular rule?

查看:44
本文介绍了排序列表<T>对象的特定规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个清单:

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.

推荐答案

有两种方式:

  1. Country 实施 java.util.Comparable 接口,用于在 Country 对象上定义自然排序,即创建对象本身知道"他们的顺序.然后您可以使用 Collections.sort(List) 或者只是从你的 List 切换到一个 SortedSet 实现,比如 TreeSet> (如果你不需要重复,Set 会丢弃重复)

  1. Have Country implement the java.util.Comparable interface to define a natural ordering on your Country objects, i.e. make the objects themselves "know" their ordering. You can then use Collections.sort(List) or just switch from your List to a SortedSet implementation like TreeSet (if you don't need duplicates, a Set drops duplicates)

编写一个java.util.Comparator 定义一个强制排序并调用Collections.sort(List, Comparator) 或 (再次丢失重复项)选择 new TreeSet(Comparator).

实现这两个中的一个就足以解决您的问题——ComparableComparator 都可以结合使用,但是:使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆