How do Backed Collections work in Java?
In Java, I have the following "integerArray" and add 2 integers to it.
Integer[] integerArray = new Integer[3];
integerArray[0] = 1;
integerArray[1] = 2;
Now I am creating a list from an array.
List<Integer> integerList = Arrays.asList(integerArray);
At this point, "integerList" contains 1 and 2.
Now I am adding another item to the array.
integerArray[2] = 3;
At this point, if we look at integerList, we can 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 supported by the specified array
This means that the returned list object, which in fact is ArrayList
, has a reference to the array, not a copy. Since it has a reference to this array, any changes to it will be reflected in the list.
The method Arrays.asList
simply calls the constructor ArrayList
, defined like this:
ArrayList (E[] array) {
if (array == null)
throw new NullPointerException();
a = array;
}
So the field will a
store a reference to your initial array.
This is because it is the same variable, but used as a list. If you are reading the Javadoc for Arrays.asList ()
He clearly indicates
Returns a fixed-size list supported by the specified array. (Changes to the returned "write through" list to an array.) This method acts as a bridge between the array and collection APIs in conjunction with Collection.toArray (). The returned list is serializable and implements RandomAccess.
Arrays.asList
is a static / utility method that calls the constructor to create a new ArrayList. ArrayList is backed by an array. This is the case in many programming languages โโwhere preliminary data structures are simply backed up by primitive arrays. You can see the source code of Arrays.asList here