You don't even know the famous bug in JDK8, how dare I give you a raise

When the author researched the JDK source code, I noticed that the following bug words appeared in the constructors of CopyOnWriteArrayList and ArrayList


6260652 actually represents the number in the JDK bug list

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6260652

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6515694

The above two bugs are actually the same problem. So what does he mean, JDK actually left this bug in 8 and hasn't dealt with it yet?

Look at a few examples:

Case 1


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();
    }
}

Each element in the parent class array is a subclass object, so as shown below, this upward transformation will not report an error

Allow subclass arrays to be converted to parent class arrays.

However, the element types in the array are all Child types, so as shown below, an error will be reported!!!


java.lang.ArrayStoreException

Indicates that an attempt has been made to store an object of the wrong type into an array of objects.

For example, the following code generates an ArrayStoreException

This means that the Object[] array does not mean that you can put an Object object in it, but depends on the actual type of the elements in the array.

Case 2


Listlist = Arrays.asList("JavaEdge"); // The returned type is java.util.Arrays$ArrayList, not ArrayList

Object[] objects = list.toArray(); // return String[] array

So we can't put the Object object into the objects array.

Case 3


ArrayList's toArray() returns an Object[] array, so any object can be stored in the list2Array array.

Summarize

From Cases 2 and 3, it can be concluded that:

for

ListstringList

when calling

Object[] objectArray = stringList.toArray()

objectArray is actually not necessarily of Object[] type, so you can't just put an object in it.

So the source code at the beginning has comments:

c.toArray might (incorrectly) not return Object[] (see 6260652)。

Through the if judgment, avoid the wrong array type storage exception.

Arrays.copyOf(elementData,size, Object[].class)

It can ensure that the Object[] array is created, so any type of object can be stored.


Fan benefits


In order to give back to the hard-core fans, I have compiled a complete software testing video learning tutorial for you. Friends can get it for free if they need it [Guaranteed 100% free]

Guess you like

Origin blog.csdn.net/m0_53918927/article/details/131013532