I have some design problems with Java Comparator Interface.
I have a class which contains a Set of a simple custom data structure:
class data {
Long ID;
int Priority;
...
}
IDs are unique, so it is possible to get the whole data using ID.
and the container class:
class Container {
Set<data> mySet = ...;
List<Long> myList = ...;
...
}
for some inevitable reasons, I need to keep a sorted List of data IDs in parallel. I need the List to be sorted by Priority.
Since, the Comparator should compare Prioritys it should implements Comparator<int>. But the List only contains IDs and the Prioritys are not available directly.
This is the problem. There is only ID in the List. Therefore, the Comparator class has no access to Priority.
How can I design such concept?
You could use something that smells like higher order functions. That is, make a static function that takes a map of sorts from Long to int (which is the priority) or data and returns a new Comparator.
The class Foo has a static method
getComparatorwhich takes an Orange. An Orange is a class that has a methodgetPrioritywhich takes an ID an return the corresponding priority. ThegetComparatormethod constructs a newComparatorobject. The newComparatorobject’scomparemethod takes two IDs. It looks up the corresponding priorities of the two IDs and compares them.My java is a bit rusty so the code may be flawed. The general idea should work, though.
Usage:
I have not given an example on how an Orange could look.