【问题标题】:How do generics affect possible Parameters/Return types泛型如何影响可能的参数/返回类型
【发布时间】:2013-11-19 07:26:29
【问题描述】:

我正在准备考试,有以下问题:

考虑以下代码和继承层次结构:

public Deque<E> theMethod(E arg1, ArrayDeque<E> arg2)
{
return theOtherMethod(arg1, arg2);
}



D<|----E<|----F

Collection<|----------------------Deque<|----------------
    ^                               ^                   |
    |                               |                   |
    |                     |------ArrayDeque             |
    |                     |                             |
    |                     |                             |
    |                     |                             |
AbstractCollection<|------|                             |
                          |                             |
                          ----AbstractList<|----------LinkedList



Considering only the classes shown above:
(a) What types of objects can you supply to theMethod as arguments?
(b) What could the declared parameter types of theOtherMethod be?
(c) What could the declared return type of theOtherMethod be?

希望 UML 是可读的,

我的答案如下,但我不确定它们是否正确,因为我不了解泛型如何影响可能的参数和返回类型。

(a) First param: E and F, second param only ArrayDeque
(b) First param: could be D or E, second param: could be Collection, Deque, ArrayDeque or AbstractCollection
(c) Collection or Deque

【问题讨论】:

  • 请为DEF 使用不同的名称。目前我把它与类型参数混淆了。
  • Deque&lt;E&gt;ArrayDeque&lt;E&gt; 怎么样?
  • 我认为这意味着它们是泛型的?
  • 你从哪里得到这个问题的? Deque&lt;E&gt;不应该是Deque&lt;Echo&gt;,否则应该为方法声明类型参数E
  • 我理解 代表通用,这可能与 Echo 类无关?

标签: java oop generics inheritance


【解决方案1】:

a: theMethod 需要一个 E 类型的对象和一个由相同类型 E 组成的 ArrayDeque。

所以如果你要为 E 使用一个字符串,那么第二个参数应该是: ArrayDeque&lt;String&gt;。泛型是为了确保它们属于同一类型!

请注意,如果您的 theMethod 方法在泛型类中,它应该与您在初始化期间传递给您的类的 E 类型相同:

public class Test<E> {
}

b:第一个参数必须是 E。第二个参数可以是:Deque&lt;E&gt; or ArrayDeque&lt;E&gt;.

c: theOtherMethod的返回类型可以是:

ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList

但在你的情况下,根据你的图表,它只能是:

ArrayDeque or LinkedList

因为它们都实现了 Deque 类。

如果您在使用泛型时遇到问题,我还建议您阅读以下内容: http://docs.oracle.com/javase/tutorial/extra/generics/index.html

【讨论】:

  • 感谢 cmets。我应该说它们返回的类仅限于 UML 图中的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多