1, the background
When I looked at JDK source code, I noticed the following bug in the constructors of both CopyOnWriteArrayList and ArrayList
6260652 actually represents the number in the JDK bug list
- Bugs.java.com/bugdatabase…
- Bugs.java.com/bugdatabase…
The above two bugs are actually the same problem. So what does it mean that the JDK left this bug in 8?
Look at a few examples:
Case 2,
2.1 a case
package com.javaedge; public class Test { public static void main(String[] args) { Child[] childArray = {new Child(), new Child()}; System.out.println(childArray.getClass()); Father[] fatherArray = childArray; System.out.println(fatherArray.getClass()); // ArrayStoreException fatherArray[0] = new Father(); }}Copy the code
Each element in the superclass array is a subclass object, so this upcast does not report an error, as shown below
Allows subclass arrays to be converted to superclass arrays.
The element type in the array is Child, so the following is an error!!
Java. Lang. ArrayStoreException shows that have tried to make the wrong type of object stored in the array of objects.
For example, the following code generates an ArrayStoreException
This means that an Object[] array does not mean you can put any Object in it, but depends on the actual type of the elements in the array.
2.2 second case
List
list = Arrays.asList(“JavaEdge”); Java.util.Arrays$ArrayList instead of ArrayList
Object[] objects = list.toArray(); // Returns a String[] array so we can’t put an Object in a Objects array.
2.3 case three
ToArray () of ArrayList returns an array of Object[], so you can store any Object into the list2Array array.
3, summarize
Conclusions can be drawn from cases two and three:
for
List<String> stringList
When calling
Object[] objectArray = stringList.toArray()
ObjectArray doesn’t actually have to be of type Object[], so you can’t just put an Object into it.
So the source code in the beginning is commented:
C. Toarray might (incorrectly) not return Object[] (see 6260652).
Use if to avoid incorrect array type storage exceptions.
Arrays.copyOf(elementData, size, Object[].class)
Make sure you create an Object[] array, which can store objects of any type.
Links:
Blog.csdn.net/qq_33589510…
Source: CSDN