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 http://bugs.sun.com/bugdatabase/view_bug.do?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.
We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.
Using the add() method to create ArrayList of objects in java. You can simply use add() method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.
But ArrayList is a parameterized type. A parameterized type can take a type parameter, so that from the single class ArrayList, we get a multitude of types including ArrayList<String>, ArrayList<Color>, and in fact ArrayList<T> for any object type T.
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[]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With