I've opened java.util.ArrayList source code, and I can't understand one thing: why elementData[] array is of type Object if ArrayList is parametrized?
public class ArrayList<E> extends ... {
.........
private transient Object[] elementData;
.........
public boolean add(E e) {/*More code*/}
}
Question: Why don't define elementData as:
private transient E[] elementData
*what advantages and disadvantages?
Everytime that you create a List with raw type, like :
List
<MyObject>list = new ArrayList<MyObject>();
The contructor converts all data into a array that must be an Object[] array, on:
public ArrayList(Collection
<? extends E>c) { elementData = c.toArray(); ...
I think this happens because ArrayList can be initialized with no raw types, like on:
List list = new ArrayList();
list.add(new String("VALUE"));
list.add(new Integer("1"));
for (Object c : list) {
System.out.println(c.toString());
}
and you can put more than one type of object inside.
Also, ArrayList uses the
Arrays.copyOf(elementData, size);
to manage some operations, which will return an Object[].
You may also take a look here and here like Paul said.
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