3

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?

Paul Bellora
  • 51,514
  • 17
  • 127
  • 176
VB_
  • 43,322
  • 32
  • 111
  • 238

1 Answers1

1

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.

Community
  • 1
  • 1
Deividi Cavarzan
  • 9,814
  • 13
  • 61
  • 78