泛型 - ArrayList中toArray()为什么不支持强制类型转换?[Java]
黄舟
黄舟 2017-04-18 10:42:06
0
4
648
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
伊谢尔伦

(T[]) Arrays.copyOf(elementData, size, a.getClass()); 强转可以成功是因为数组的类型本身就为a.getClass().

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings("unchecked")
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

Array object (of target type) created by Array.newInstance(newType.getComponentType(), newLength).


String[] y = (String[]) x.toArray()无法强制转换是因为array的数据类型为Object[]而不是String[].

伊谢尔伦

StringObject 的子类,但是 String[] 不是 Object[] 的子类,所以对于实际类型是 StringObject 引用是可以强转成 String 的。但是 Object[] 怎么都不能强转成 String[],只能采用个个赋值的方式,把里面的引用挨个强转再拷贝过来(当然可以用 Arrays.copyOf() Let’s do this.

伊谢尔伦

It is legal to convert the value of the subclass back to the subclass

Cast the value of Object[] into String[], this behavior is similar to (Integer)(new Object())

阿神

The generic type of ArrayListE is not required when the generic type is not specified, for example:

ArrayList list = new ArrayList();
list.add("test");
list.add(123);
list.add(11.22);

In this case, the second method is not applicable, and there is no way to perform forced type conversion

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template