Arrays.asList(temp)
It takes an arrayia
and creates a wrapper that implementsList<String>
, which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, someList
operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.Note that the list wrapper doesn't extendArrayList
- it's a different kind of object.ArrayList
s have their own, internal array, in which they store their elements, and are able to resize the internal arrays etc. The wrapper doesn't have its own internal array, it only propagates operations to the array given to it. On the other hand, if you subsequently create a new array asnew ArrayList<String>(Arrays.asList(temp
))then you create newArrayList
, which is a full, independent copy of the original one. Although here you create the wrapper usingArrays.asList
as well, it is used only during the construction of the newArrayList
and is garbage-collected afterwards. The structure of this newArrayList
is completely independent of the original array. It contains the same elements (both the original array and this newArrayList
reference the same integers in memory), but it creates a new, internal array, that holds the references. So when you shuffle it, add, remove elements etc., the original array is unchanged.
Wednesday, 11 January 2017
What is the best way of using Arrays.asList() to initialize a List.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment