When we create a list from an array using java.util.Arrays.asList() , the list is mutable.
Yes and no: The list may be modified, by calling
list.set(index, element);
But the list may not be structurally modified. That means that it is not possible to add elements to the list or remove elements from the list. The reason simply is that the list is still backed by the array, and the size of the array may not change.
When we need a fixed size mutable collection we go for Array
And that's the key point here: An array is not a Collection. The Arrays.asList
method mainly serves as a "bridge" between the "arrays world" and the "collections world".
The Arrays.asList
method allows you, for example, the pass data to a method that expects a Collection
:
// A method that expects a collection:
void process(List<String> strings) { ... }
void call()
{
String array[] = new String[] { "A", "B", "C" };
// Pass the array (as a list) to the method:
process(Arrays.asList(array));
}
This application case includes creating other collections from an array. For example, if you have an array and want to create a Set
containing the elements from the array, you could to
String array[] = new String[] { "A", "B", "C" };
Set<String> set = new HashSet<String>();
for (String s : array)
{
set.add(s);
}
But with the Arrays.asList
method, this can be done more conveniently:
Set<String> set = new HashSet<String>(Arrays.asList(array));
The Arrays.asList
method is so to say the counterpart of the Collection#toArray method, which works in the opposite direction (although this method usually involves creating and filling a new array, whereas the Arrays.asList
method just "wraps" an array and lets it "look like" a List
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…