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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With