84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
人生最曼妙的风景,竟是内心的淡定与从容!
(T[]) Arrays.copyOf(elementData, size, a.getClass()); 强转可以成功是因为数组的类型本身就为a.getClass().
(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).
Array.newInstance(newType.getComponentType(), newLength)
String[] y = (String[]) x.toArray()无法强制转换是因为array的数据类型为Object[]而不是String[].
String[] y = (String[]) x.toArray()
array
Object[]
String[]
String 是 Object 的子类,但是 String[] 不是 Object[] 的子类,所以对于实际类型是 String 的 Object 引用是可以强转成 String 的。但是 Object[] 怎么都不能强转成 String[],只能采用个个赋值的方式,把里面的引用挨个强转再拷贝过来(当然可以用 Arrays.copyOf() Let’s do this.
String
Object
Arrays.copyOf()
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())
(Integer)(new Object())
The generic type of ArrayListE is not required when the generic type is not specified, for example:
E
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
(T[]) Arrays.copyOf(elementData, size, a.getClass());
强转可以成功是因为数组的类型本身就为a.getClass()
.Array object (of target type) created by
Array.newInstance(newType.getComponentType(), newLength)
.String[] y = (String[]) x.toArray()
无法强制转换是因为array
的数据类型为Object[]
而不是String[]
.String
是Object
的子类,但是String[]
不是Object[]
的子类,所以对于实际类型是String
的Object
引用是可以强转成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 ArrayList
E
is not required when the generic type is not specified, for example:In this case, the second method is not applicable, and there is no way to perform forced type conversion