本文介绍了ArrayList.toArray()中的Java泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个数组列表定义如下:

  ArrayList< String> someData = new ArrayList<>(); 

后来在您的代码中,由于泛型,您可以这样说:

  String someLine = someData.get(0); 

编译器知道它会得到一个字符串。耶泛型!但是,这会失败:

  String [] arrayOfData = someData.toArray(); 

toArray()将始终返回一个数组对象,而不是定义的泛型。为什么 get(x)方法知道它正在返回什么,但是 toArray()默认为Objects?如果你看看 toArray(T [] a)的实现, 类,它是例如:

  public< T> T [] toArray(T [] a){
if(a.length< size)
//创建一个新的运行时类型数组,但是我的内容:
return(T [])Arrays.copyOf(elementData,size,a.getClass());
System.arraycopy(elementData,0,a,0,size);
if(a.length>大小)
a [size] = null;
返回a;





$ b

这个方法的问题在于你需要传递相同泛型类型的数组。现在考虑这种方法是否没有任何争论,那么实现将类似于以下内容:

  public< T> T [] toArray(){
T [] t = new T [size]; //编译错误
返回Arrays.copyOf(elementData,size,t.getClass());
}

但是这里的问题是你不能在Java ,因为编译器不确切知道 T 表示的内容。换句话说创建不可修饰类型的数组()在Java中不允许使用 另外一个重要的引用来自 Array Store Exception ()。

因此,不应重写 toArray(),您应该使用 toArray (T [] a)



可能对您很有趣。


Say you have an arraylist defined as follows:

ArrayList<String> someData = new ArrayList<>();

Later on in your code, because of generics you can say this:

String someLine = someData.get(0);

And the compiler knows outright that it will be getting a string. Yay generics! However, this will fail:

String[] arrayOfData = someData.toArray();

toArray() will always return an array of Objects, not of the generic that was defined. Why does the get(x) method know what it is returning, but toArray() defaults to Objects?

解决方案

If you look at the implementation of toArray(T[] a) of ArrayList<E> class, it is like:

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

Problem with this method is that you need to pass array of the same generic type. Now consider if this method do not take any argument then the implementation would be something similar to:

public <T> T[] toArray() {
    T[] t = new T[size]; // compilation error
    return Arrays.copyOf(elementData, size, t.getClass());
}

But the problem here is that you can not create generic arrays in Java because compiler does not know exactly what T represents. In other words creation of array of a non-reifiable type (JLS §4.7) is not allowed in Java.

Another important quote from Array Store Exception (JLS §10.5):

That is why Java has provided overloaded version toArray(T[] a).

So instead of overriding toArray(), you should use toArray(T[] a).

Cannot Create Instances of Type Parameters from Java Doc might also be interesting for you.

这篇关于ArrayList.toArray()中的Java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 06:09