Java泛型和无限(可比)

Fla*_*ins 5 java generics comparable infinity

使用Integer类型,您可以执行以下操作:

int lowest = Integer.MIN_VALUE;
Run Code Online (Sandbox Code Playgroud)

如果我使用泛型,我该怎么办?

K lowest = <...>;
Run Code Online (Sandbox Code Playgroud)

我需要这个来实现类似于PriorityQueue的东西.我可以访问我想要从队列中删除的节点,但它不是min.

1. I need to make it the min by decreasing the key of that node,
2. And then remove the min.
Run Code Online (Sandbox Code Playgroud)

我坚持第一步.我唯一能做的就是将节点的键设置为当前最小值.不确定它是否足够.

Ale*_*x B 5

所有 Comparable 类型都没有通用形式MIN_VALUEMAX_VALUE适用于所有 Comparable 类型。

考虑一个Time实现可比较的类。没有MAX_VALUE时间,即使它是可比的。


Ada*_*ter 5

我试图想象什么场景需要这种行为。这是我能想到的最好的了...

警告:此代码是危险的。请怜悯我张贴这种可憎的东西。这只是一个概念证明。

public class Lowest<K> implements Comparable<K> {
    public int compareTo(K other) {
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

进而...

public class Test {
    public <K extends Comparable<K>> K findMaximum(List<K> values) throws Exception {
        K lowest = (K) new Lowest<K>(); /// XXX DANGER! Losing compile-time safety!!!

        K maximum = lowest;
        for (K value : values) {
            if (maximum.compareTo(value) < 0) {
                maximum = value;
            }
        }

        if (maximum == lowest) {
            throw new Exception("Could not find a maximum value");
        } else {
            return maximum;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Eoi*_*ell 4

这没有任何意义...

鉴于您当时不知道 K 是什么,(即您一般地实现它......废话!)您无法为其指定最小/最大界限。

在 K 可能是 int、long、string OR 对象的情况下,您无法明智地猜测使用

Integer.MIN_VALUE、“”或 NULL。

我猜您正在寻找的是 K.MIN_VALUE_OF_EVENTUAL_TYPE 但它不存在。

  • 这可能是来自 C++ 背景的人,其中仅使用 numeric_limits&lt;K&gt;::max 和 numeric_limits&lt;K&gt;::min 是微不足道的。这使您可以编写处理字符、双精度数、整数、64 位整数甚至自定义数字类的代码。 (2认同)