我有abstract class OptionalComparator<T extends Comparable<T>> implements Comparator<Optional<T>>
到现在为止还挺好。

遵循Optional本身使用的模型,我认为最好有一个此类的实例,并在必要时进行强制转换(例如,转换为OptionalComparator<Integer>)。

所以我做了private static final OptionalComparator<? extends Comparable<?>> ABSENT_FIRST

当我尝试分配值时,麻烦就来了。类型应该是什么?
new OptionalComparator<Comparable<Object>>() {...}不起作用。
new OptionalComparator<Comparable<Comparable<Object>>>() {...}不起作用。

例如,new OptionalComparator<Integer>() {...}确实可以工作,但是我想要尽可能少的特定类型。

我究竟做错了什么?如何制作此类的基本案例?

最佳答案

您可以像这样实现OptionalComparator的多种实现:

private static final OptionalComparator<? extends Comparable<?>> ABSENT_FIRST = new AbsentFirst<>();

private static final OptionalComparator<? extends Comparable<?>> ABSENT_LAST = new AbsentLast<>();

private interface OptionalComparator<T extends Comparable<T>> extends Comparator<Optional<T>> { }

private static class AbsentFirst<T extends Comparable<T>> implements OptionalComparator<T> {
    @Override
    public int compare(Optional<T> obj1, Optional<T> obj2) {
        if (obj1.isPresent() && obj2.isPresent()) {
            return obj1.get().compareTo(obj2.get());
        } else if (obj1.isPresent()) {
            return -1;
        } else if (obj2.isPresent()) {
            return 1;
        } else {
            return 0;
        }
    }
}

private static class AbsentLast<T extends Comparable<T>> implements OptionalComparator<T> {
    @Override
    public int compare(Optional<T> obj1, Optional<T> obj2) {
        if (obj1.isPresent() && obj2.isPresent()) {
            return obj1.get().compareTo(obj2.get());
        } else if (obj1.isPresent()) {
            return 1;
        } else if (obj2.isPresent()) {
            return -1;
        } else {
            return 0;
        }
    }
}

static <T extends Comparable<T>> OptionalComparator<T> absentFirstComparator() {
    @SuppressWarnings("unchecked")
    OptionalComparator<T> comp = (OptionalComparator<T>) ABSENT_FIRST;
    return comp;
}

static <T extends Comparable<T>> OptionalComparator<T> absentLastComparator() {
    @SuppressWarnings("unchecked")
    OptionalComparator<T> comp = (OptionalComparator<T>) ABSENT_LAST;
    return comp;
}

public static void main(String... args) {
    OptionalComparator<Integer> absentFirstInt = absentFirstComparator();
    System.out.println(absentFirstInt.compare(Optional.of(1), Optional.empty()));

    OptionalComparator<Integer> absentLastInt = absentLastComparator();
    System.out.println(absentLastInt.compare(Optional.of(1), Optional.empty()));

    OptionalComparator<Double> absentFirstDouble = absentFirstComparator();
    System.out.println(absentFirstDouble.compare(Optional.of(1.0), Optional.empty()));

    OptionalComparator<Double> absentLastDouble = absentLastComparator();
    System.out.println(absentLastDouble.compare(Optional.of(1.0), Optional.empty()));
}

输出:
-1
1
-1
1

09-11 17:34