开发者

Sorting an ArrayList based on a field?

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))?

thanks


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

e.g.

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?).

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.


You can use the Collections.sort() method for sorting, if you implement the Comparator interface for the objects which need to be compared.


Check out the Bean Comparator for a couple of options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜