Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in java.util.ArrayList [duplicate]

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?

like image 795
VB_ Avatar asked Nov 29 '25 04:11

VB_


1 Answers

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.

like image 118
Deividi Cavarzan Avatar answered Nov 30 '25 16:11

Deividi Cavarzan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!