SF..MJ
SF..MJ

Reputation: 880

how arraylist is heterogeneous if it internally uses Object[] Array

arraylist internally uses Object[] Array which is homogeneous then how arraylist is heterogeneous

The following throws an exception when running:

Object[] array = new String[3];
array[0] = "a";
array[1] = 1;   // throws java.lang.ArrayStoreException

unlike the following which compiles and runs without problem

ArrayList list = new ArrayList<String>();
list.add("a");
list.add(1);    // works
list.add(new Object());  // works

Upvotes: 1

Views: 2008

Answers (3)

Eran
Eran

Reputation: 393781

The backing array of an ArrayList is an Object[] (i.e. the element type of that array is the Object class, not any sub-class of Object), so you can put any reference type (as well as primitives, which get auto-boxed to their corresponding wrapper type) in it.

The following would not throw an exception:

Object[] array = new Object[3];
array[0] = "a";
array[1] = 1;

You can see the initialization of the backing array in the ArrayList constructor:

public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity]; // here
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

Upvotes: 4

ssaa
ssaa

Reputation: 1112

since it is holding Object which is parent of all classes so eventually we are make homogeneous to heterogeneous. And this is is not the ideal way to define arraylist. But technically we can do.

Upvotes: 0

Jai
Jai

Reputation: 8363

Generics are compile-time feature of the Java Language. At runtime, all defined generic types are considered to be of Object type. Therefore, using Object[] as the backing supporting list makes perfect sense.

Doing these two compiles to the same thing (same bytecode):

ArrayList<String> list = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();

On the other hand, array types are consistent through compile and run time. These will produce different bytecode after compiling:

String[] arr = new String[];
Integer[] arr = new Integer[];

Upvotes: 0

Related Questions