hap497
hap497

Reputation: 162965

Need help in passing Java Generics to Collections.sort()

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?

Upvotes: 0

Views: 717

Answers (3)

Nicholas Jordan
Nicholas Jordan

Reputation: 656

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.

Upvotes: 0

CPerkins
CPerkins

Reputation: 9018

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;
        }
    });

Upvotes: 1

Fredrik
Fredrik

Reputation: 5839

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

Upvotes: 10

Related Questions