Reputation: 217
I have a particular class, let's call it ClassX. ClassX is a simple little class; it has a few data members, a constructor, and (less simply) a nested class. The nested class is specifically for defining a comparator, and is written in this way:
public static Comparator<ClassX> classXComparator = new Comparator<ClassX>()
{
public int compare(ClassX x1, ClassX x2)
{
//code that compares two data members and returns -1 for x2>x1, 1 for x1>x2,
//0 for x1 = x2
}
}
I also have another class, let's call it ClassA. ClassA is the main class of my project, and has an ArrayList of ClassXs called entries. I want to call Collections.sort() on entries; however, I just can't figure out how. The list of things I've tried includes:
Collections.sort(entries, ClassX.classXComparator.compare(ClassX, ClassX));
Collections.sort(entries, ClassX.classXComparator.compare(ClassX a, ClassX b));
Collections.sort(entries, classXComparator.compare());
Collections.sort(entries, ClassX.compare(ClassX, ClassX));
I'm stumped. Could someone help me out?
Upvotes: 1
Views: 93
Reputation: 726639
To understand what's happening look at the declaration of classXComparator
:
public static Comparator<ClassX> classXComparator = <something>
This declares classXComparator
as a static
field of type Comparator<ClassX>
, which is precisely the type of the second argument of sort(...)
. Therefore, the invocation of sort
should be as follows:
Collections.sort(entries, ClassX.classXComparator);
Upvotes: 1