Reputation: 431
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.
Upvotes: 3
Views: 519
Reputation: 2865
Arrays.asList
is a static/utility method that invokes the constructor to create a new ArrayList. The ArrayList is backed by an Array. This is the case in a lot of programming languages, where advance data structures are simply backed by primitive arrays. You can look at the source code here Arrays.asList
Upvotes: 2
Reputation: 72844
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.
Upvotes: 4
Reputation: 6816
This is because it is the same variable but used as a list. If you read the Javadoc for Arrays.asList()
It states clearly
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
Upvotes: 4