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

查看:154
本文介绍了排序列表< 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. 国家实施的 java.util.Comparable 接口定义的自然顺序国家对象,即让对象本身知道自己的排序。然后,您可以使用<一个href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29\"相对=nofollow> Col​​lections.sort(名单) 或从你的列表只需切换来一的SortedSet 实施如 TreeSet的(如果你不需要重复,一个设置滴重复)

  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 来定义的订货实行并调用<一个href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"相对=nofollow> Col​​lections.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屋!

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