简体   繁体   中英

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.

eg

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.

如果为需要比较的对象实现Comparator接口,则可以使用Collections.sort()方法进行排序。

签出Bean Comparator几个选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM