我将在此处发布一个链接: Collections.sort()
。 SO 上有很多关于 PECS 范式的帖子,包括 this one 。在我自己的个人代码中,我经常使用泛型,但只使用过 P 部分(即 <X extends SomethingElse>
)。
Collections.sort
期望作为其泛型参数 <T extends Comparable<? super T>>
。我看不出super
在哪里在那里踢。你有一个具体的例子来说明为什么这是必要的吗?
当我这样做时,我非常担心我也不理解 P 的全部含义...我已经阅读了很多很多链接,但没有明确、明显的证明 P 是 P 和 C是C...
编辑至于这里可能已经有了答案”:不,抱歉。我已阅读此链接以及其他许多链接。这仍然没有告诉我这一切背后的核心机制.到目前为止给我的两个答案给了我提示,实际上比我迄今为止能找到的所有链接都给了我更多提示。
最佳答案
例如
List<Interger> myIntegers = Arrays.asList(5, 2, 3);
List<Long> myLongs = Arrays.asList(5L, 2L, 3L);
MyNumberComparator myNumberComparator = new Comparator<Number>(){...}
Collections.sort(myIntegers, myNumberComparator ); // Number is "super" class of Integer
Collections.sort(myLongs , myNumberComparator ); // Number is "super" class of Long
因此,这里的“super”允许重用 MyNumberComparator 来排序整数和排序长整型。
关于Java、泛型和 PECS : still having trouble understanding the C part; concrete example?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17192772/