0

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

asked Nov 22, 2010 at 2:44

3 Answers 3

4

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.

answered Nov 22, 2010 at 2:54
Sign up to request clarification or add additional context in comments.

Comments

2

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

answered Nov 22, 2010 at 2:54

Comments

0

Check out the Bean Comparator for a couple of options.

answered Nov 22, 2010 at 2:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.