gpt4 book ai didi

java - Optional 的比较器

转载 作者:行者123 更新时间:2023-12-03 21:34:43 26 4
gpt4 key购买 nike

我有 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

关于java - Optional<T> 的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com