String[] arr = { "Java", "Champ", "." };
List<String> list = (List<String>) Arrays.asList(arr); // line 1
arr[2] = ".com"; // line 2
for (String word : list) {
System.out.print(word);
}
How this results output as JavaChamp.com
even it is converted into List in line 1 and modified in line 2
Arrays.asList
doesn't copy the array into a list - it creates a view onto the array. Any change you make via the list affects the array, and vice versa. That's why you can't add to (or remove from) the list returned by Arrays.asList
- because the array itself can't change size.
The documentation makes this clear in one direction:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
... but it works both ways, because the list just has no dedicated backing storage. It really is just backed by the array.
See more on this question at Stackoverflow