tags:

views:

185

answers:

3

Hi,

I need help in passing a Java Generics List to Collections.sort(). Here is my code:

List<MyObject> orgMyObjectList = new ArrayList<MyObject>();
Collections.sort(orgMyObjectList, new Comparable<MyObject>() {

        public int compareTo(MyObject another) {
            // TODO Auto-generated method stub
            return 0;
        }
    });

But I get this compiler error in eclipse: The method sort(List, Comparator) in the type Collections is not applicable for the arguments (List, new Comparable< MyObject >(){})

Can you please tell me how to fix it?

+9  A: 

You're passing in a Comparable when it wants a Comparator.

Fredrik
+1  A: 

As Fredrik said, Collections.sort() needs a Comparator. Making it right looks like this:

    List orgMyObjectList = new ArrayList();
    Collections.sort(orgMyObjectList, new Comparator() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            // TODO Auto-generated method stub
            return 0;
        }
    });
CPerkins
+1 for the auto-generated example.
Fredrik
A: 

Yes, two issues. One is as noted: Comparator vs Comparable ( and don't forget equals )

The other is that posting with // TODO Auto-generated method stub shows that you have a lot of work to do. That is telling you that you need to write the compare operation.

Better start with something remarkably simple, pull this problem to a test / development program that you wrote just for studying the issue.

Nicholas Jordan