I believe you can use one single comparator object for your purposes.
I assume that your comparator implementation IntervalComparator
is stateless (in the sense that it has no fields to store anything). In this case you can always use the very same code to do the comparison.
final class IntervalComparator<T extends Comparable<T>> implements
Comparator<Interval<T>> {
// Private constructor. Use the getInstance method instead.
private IntervalComparator() {
}
private static IntervalComparator INSTANCE = new IntervalComparator();
@SuppressWarnings("unchecked")
public static <K extends Comparable<K>> IntervalComparator<K> getInstance() {
return (IntervalComparator<K>)INSTANCE;
}
@Override
public int compare(Interval<T> o1, Interval<T> o2) {
// ... Comparison code goes here ...
}
}
Your use case would then be as follows:
private Set<Interval<T>> intervalSet;
private IntervalUnion() {
this.intervalSet =
new TreeSet<Interval<T>>(
IntervalComparator.<T>getInstance());
// ... add Interval<T> objects into intervalSet ...
}
Note that there is an annotation @SuppressWarnings("unchecked")
at the polymorphic getInstance()
method. This is to surpress the compiler warning that the cast occurring in the method cannot be checked due to type erasure in Java generics.
By the way, there is a prominent persuasive precedent for such an implementation. The method java.util.Collections.emptyList()
is similarly implemented:
@SuppressWarnings("unchecked")
public static final List EMPTY_LIST = new EmptyList<>();
// ...
@SuppressWarnings("unchecked")
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
(cf. http://www.docjar.com/html/api/java/util/Collections.java.html#3161)