String[] dogs = {"fido", "clover"}; List dogList = Arrays.asList(dogs); dogList.add("spot"); dogs[0] = "fluffy"; System.out.println(dogList); for(String s: dogs) { System.out.print(s + " "); }
It gives Exception on adding element in List . Please Explain..
The line dogList.add("spot"); should fail with an UnsupportedOperationException, because the list returned by Arrays.asList is not modifiable. You can see this by referring to the documentation of Arrays.asList which says this:
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.
See? It's a fixed-size list, and you are not allowed to alter it.
We cant use add() or remove() method
But we can use set() method ..
Right?
Correct. Values of the keys are not immutable. It's only the size which is fixed as mentioned in the documentation.