gpt4 book ai didi

java - 将 Comparable 从 Comparator 转换为 Comparator?

转载 作者:行者123 更新时间:2023-11-30 05:50:17 28 4
gpt4 key购买 nike

我经常有一个 Comparator 类型,而我需要一个 Comparable 类型,反之亦然。是否有可重用的 JDK API 可以相互转换?类似的东西:

    public static <C> Comparable<C> toComparable(final Comparator<C> comparator) {
// does not compile because Hidden can not extend C,
// but just to illustrate the idea
final class Hidden extends C implements Comparable<C> {
@Override
public int compareTo(C another) {
return comparator.compare((C) this, another);
}
};
return new Hidden();
}

public static <C extends Comparable<C>> Comparator<C> toComparator(final Class<C> comparableClass) {
return new Comparator<C>() {
@Override
public int compare(C first, C second) {
assert comparableClass.equals(first.getClass());
assert comparableClass.equals(second.getClass());
return first.compareTo(second);
}
};
}

最佳答案

ComparableComparator 来自 Apache Commons Collections 的地址似乎是 Comparable<T>Comparator问题(不幸的是它不是通用类型友好的)。

反向操作不太可能,因为 Comparator<T>代表算法,而 Comparable<T>代表实际数据。您将需要某种组合。快速而肮脏的解决方案:

class ComparableFromComparator<T> implements Comparable<T> {

private final Comparator<T> comparator;
private final T instance;

public ComparableFromComparator(Comparator<T> comparator, T instance) {
this.comparator = comparator;
this.instance = instance;
}

@Override
public int compareTo(T o) {
return comparator.compare(instance, o);
}

public T getInstance() {
return instance;
}
}

假设你有一个类 Foo那不是Comparable<Foo>但是你有 Comparator<Foo> .你可以这样使用它:

Comparable<Foo> comparable = new ComparableFromComparator<Foo>(foo, comparator);

如您所见(尤其是没有 mixins),它非常丑陋(我什至不确定它是否会工作...)还要注意 comparable不扩展 Foo , 你必须打电话 .getInstance()相反。

关于java - 将 Comparable 从 Comparator 转换为 Comparator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14325598/

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