Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Backed Collections work in Java?

Tags:

java

arrays

list

In Java,I have the following array 'integerArray' and add 2 integers to it.

Integer[] integerArray = new Integer[3];
integerArray[0] = 1;
integerArray[1] = 2;

Now I create a list out of the Array.

List<Integer> integerList = Arrays.asList(integerArray);

At this point,the 'integerList' contains 1 and 2.

Now I add another element to the array.

integerArray[2] = 3;

At this point,if we examine the integerList,we see that it contains 1,2,3;

What mechanism is used so that any changes to the Array are reflected in the List as well? A simple implementation or example will really help.

like image 779
Dhivya Dandapani Avatar asked Apr 21 '26 01:04

Dhivya Dandapani


1 Answers

Returns a fixed-size list backed by the specified array

This means that the returned list object, which is actually an ArrayList, has a reference to the array, as opposed to a copy. Since it has a reference to this array, any changes to it will be reflected in the list.

The method Arrays.asList just calls the constructor of ArrayList defined as follows:

ArrayList (E[] array) {
    if (array == null)
        throw new NullPointerException();
    a = array;
}

So the field a will store the reference to your initial array.

like image 191
M A Avatar answered Apr 22 '26 14:04

M A