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
  • 54,340
  • 18
  • 130
  • 181
VB_
  • 45,112
  • 42
  • 145
  • 293

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
  • 10,034
  • 13
  • 66
  • 80