Why convert a type to an array of objects in ArrayList Construction?

public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } 

The code is a java.util.ArrayList construct. you can check error details 6260652, here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6260652

My question is: if I am not converting a type, what will be the problem? Because I think it is completely OK if elementData refers to a subType array.

+7
source share
1 answer

Here is an example of what could go wrong without an appropriate conversion:

 List<Object> l = new ArrayList<Object>(Arrays.asList("foo", "bar")); // Arrays.asList("foo", "bar").toArray() produces String[], // and l is backed by that array l.set(0, new Object()); // Causes ArrayStoreException, because you cannot put // arbitrary Object into String[] 
+12
source

All Articles