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?
当您需要一个比较器时,您正在传递一个比较器。
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; } });
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.