Reputation: 487
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 the construction of java.util.ArrayList. you can check the details of bug 6260652, here https://bugs.java.com/bugdatabase/view_bug?bug_id=6260652
my question is if I don't convert the type, what problem will happen? Because I think it's totally OK if elementData refer to subType array.
Upvotes: 8
Views: 1239
Reputation: 242686
Here is an example of what may go wrong without the conversion in question:
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[]
Upvotes: 12