本文介绍了Java,泛型和PECS:仍然无法理解C部分;具体的例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会在此发布一个链接:。关于PECS模式,SO上有很多帖子,其中包括。在我自己的代码中,我使用泛型很多,但只使用过P部分(即< X extends SomethingElse> )。



Collections.sort 期望作为其泛型参数a < T extends Comparable< ;? super T>> 。我无法看到 super 在哪里进入。你有一个具体的例子说明为什么这是必要的吗?



当我在这时,我深深地害怕我不明白P的全部含义。 ..我读了很多很多的链接,没有一个明确的,明显的证据证明P是P,C是C ...

编辑

strong>至于这里可能已经有了答案:不,对不起,我已经阅读了这个链接,还有很多关于这个的链接,但是这并没有告诉我背后的核心机制,到目前为止我给出的两个答案给我提示,实际上比我目前能找到的所有链接都要好。

  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是超级类Integer
Collections.sort(my Longs,myNumberComparator); // Number是超级类Long

因此,super允许重复使用MyNumberComparator排序整数和排序Longs。


I'll post a single link here: Collections.sort(). There have been many posts on SO with regards to the PECS paradigm, including this one. In my own personal code, I use generics quite a lot, but have only ever had the use of the P part (that is, <X extends SomethingElse>).

Collections.sort expects as its generics argument a <T extends Comparable<? super T>>. I fail to see where the super kicks in in there. Do you have a concrete example of why this is necessary?

While I am at it, I am deeply afraid that I don't understand the full implications of P either... I have read many, many links, without having had a clear, obvious proof that P is P and C is C...

EDIT As to the may already have an answer here": no, sorry. I have read this link, and many others on SO. This still does not tell me the core mechanism behind it all. The two answers given to me so far give me hints, in fact more so than all the links I could find so far.

解决方案

E.g.

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

So "super" here allows to reuse MyNumberComparator for both sorting Integers and sorting Longs.

这篇关于Java,泛型和PECS:仍然无法理解C部分;具体的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:41