We help IT Professionals succeed at work.

Sorting a List of objects without implements Comparable

kristian_gr
kristian_gr asked
on
556 Views
Last Modified: 2012-05-05
Hi.
I'm tying to figure out how to sort a list of objects ex List<Test> testList. Usually I'd do "public class Test implements Comparable<Test>" and use the CompareTo method as Colllections.sort(testList).

But for other reasons my object can not impement Comparable. What is the easiest way to sort a list then?

I need the objects in my testList sorted on the variable sortNum.

test class looks like this:
public class Test() {
  private String Name;
  private int sortNum;
}
Comment
Watch Question

Commented:
you can use Comparator instead

Collections.sort(yourList, new Comparator<Test>() {

                  public int compare(Test t1, Test t2) {
                                // check whether these two Test are equal (0), greater than (1)or less than(-1)
                        return 0;
                  }

}
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.