【发布时间】:2016-02-16 17:40:20
【问题描述】:
作为一个类分配,我必须实现 AbstractCollection 的自定义实现,并使用泛型。我发现AbstractCollection.toArray()隐藏了它默认的T类型如下:
public <T> T[] toArray(T[] a) { ... }
我最初认为以下方法会起作用,但我的 IDE 告诉我它不会覆盖超级:
@Override
public T[] toArray(T[] a) { ... }
所以,然后我将<T> 添加到方法签名中,现在(尽管它会编译)被告知以下内容:
Array of type 'T[]' expected
//Reports two types of suspicious calls to Collection.toArray().
//The first type is any calls where the type of the specified array argument
// is not of the same type as the array type to which the result is casted.
//Example:
void m(List list) {
Number[] ns = (Number[])
list.toArray(new String[list.size()]);
}
//The second type is any calls where the type of the specified array argument doesn't match
// the type parameter of the collection declaration.
//Example:
void m(List<Number> list) {
Number[] ns =
list.toArray(new String[list.size()]);
}
所以,我的第一个问题是,是否有充分的理由一开始就这样做?其次,这会以任何方式影响我的实施吗?
【问题讨论】:
-
是否有任何负面的南希愿意向我解释他们为什么不赞成这个问题?我看不出有什么问题。
-
当你给
toArray()方法一个String[]时,返回值为String[],这与Number[]不兼容。如果您想要Number[],请将其作为参数。 -
@LouisWasserman 不完全是,但它可能是相关的。谢谢
-
@agent154 这几乎是您第一个问题的答案——
toArray是这样写的,因为该集合不知道 如何 创建一个适当的数组类型。