排序基于字段一个ArrayList? [英] Sorting an ArrayList based on a field?

查看:98
本文介绍了排序基于字段一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有有一些objects.also我的对象的ArrayList有两个字段(1)名称(2)成本
我要排序此ArrayList在其成本field.is那里为我做的或者我应该写我自己的任何特殊方法?还是否有针对此doeing一些方法,什么是它的时间复杂度(O(N),( O(nlogn))?

Hi I have an arrayList which has some objects.also my objects has two fields (1) name (2) cost I want to sort this arrayList with its cost field.is there any special method that do it for me or I should write it myself?also if there is some method for doeing this ,what is its time complexity(O(n),(O(nlogn))?

感谢

推荐答案

如果你喜欢类型的安全性(不使用BeanComparator),那么你需要编写自己的比较。

If you like type saftey (not using BeanComparator), then you need to write your own comparator.

例如

Collections.sort(list, new Comparator<SomeType>() {
    public int compareTo(SomeType lhs, SomeType rhs) {
        return lhs.getCost().compareTo(rhs.getCost());
    }
});

请注意,这不是空安全的(可以花费为空?)

Note, this is not null safe (can cost be null?).

另一种选择是使用BeanComparator,但一定要添加一个测试,可确保始终排序的情况下,工作方法的名称更改。

The other option would be to use BeanComparator, but make sure you add a test which makes sure that the sorting always works in case the method name changes.

这篇关于排序基于字段一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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