Reputation: 3124
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
Upvotes: 0
Views: 663
Reputation: 2579
You can use the Collections.sort()
method for sorting, if you implement the Comparator interface for the objects which need to be compared.
Upvotes: 2
Reputation: 3894
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.
Upvotes: 4