List.toArray奇仿制药的行为(T []) [英] Odd generics behaviour of List.toArray(T[])
问题描述
我遇到现在的东西非常基本但非常令人困惑来了。我需要一个列表转换为数组。该列表包含字符串
实例。采用完美的例子 List.toArray(T [])
,因为我想一个的String []
实例。这是行不通的,但是,如果没有结果明确铸造到的String []
。
I came across something very basic but extremely bewildering today. I needed to convert a list to an array. The list contained String
instances. Perfect example of using List.toArray(T[])
, since I wanted a String[]
instance. It would not work, however, without explicitly casting the result to String[]
.
作为测试场景中,我用下面的code:
As a test scenario, I used the following code:
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String args[]) {
List l = Arrays.asList("a", "b", "c");
String stuff[] = l.toArray(new String[0]);
System.err.println(Arrays.asList(stuff));
}
}
不编译。它在的的javadoc ,但是编译器说以下内容:
which does not compile. It's nearly an exact copy of the example in the javadoc, yet the compiler says the following:
MainClass.java:7: incompatible types
found : java.lang.Object[]
required: java.lang.String[]
String stuff[] = l.toArray(new String[0]);
^
如果我加入强制转换为的String []
将编译和完美运行。但是,这不是我所期望的时候我看着的toArray方法的签名:
If I add a cast to String[]
it will compile AND run perfectly. But that is not what I expect when I looked at the signature of the toArray method:
<T> T[] toArray(T[] a)
这告诉我,我不应该投。这是怎么回事?
This tells me that I shouldn't have to cast. What is going on?
编辑:
奇怪的是,如果我更改列表声明:
Curiously, if I change the list declaration to:
List<?> l = Arrays.asList("a", "b", "c");
它也可以。或列表与LT;对象&gt;
。所以它并没有成为一个列表与LT;弦乐&GT;
的建议。我开始觉得用原料列表
键入也怎么变化这个类里面工作泛型方法。
it also works. Or List<Object>
. So it doesn't have to be a List<String>
as was suggested. I am beginning to think that using the raw List
type also changes how generic methods inside that class work.
第二个编辑:
我觉得我得到它了。什么汤姆Hawtin在评论中写道下面似乎是最好的解释。如果您在原始的方式使用泛型类型,从该实例的所有泛型信息将被编译器删除。
I think I get it now. What Tom Hawtin wrote in a comment below seems to be the best explanation. If you use a generic type in the raw way, all generics information from that instance will be erased by the compiler.
推荐答案
您忘了指定类型参数列表:
you forgot to specify the type parameter for your List:
List<String> l = Arrays.asList("a", "b", "c");
在这种情况下,你可以写安全性:
in this case you can write safety:
String[] a = l.toArray(new String[0]);
无需任何转换。
这篇关于List.toArray奇仿制药的行为(T [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!