Converting an array to a list of errors

can someone explain to me what is going on in the following lines of code and why it works?

Integer[] myray = {1,2,3,4,5};
List<Integer> l = new ArrayList<Integer>(Arrays.asList(myray));
l.add(6);
System.out.println(l);

      

This code works fine. It converts the array to a list and then adds another element. But the next code dose doesn't work

Integer[] myray = {1,2,3,4,5};
List<Integer> l = (Arrays.asList(myray));
l.add(6);
System.out.println(l);

      

The above code is giving me the following error: Exception on thread "main" java.lang.UnsupportedOperationException Can someone please tell me the difference between the two conversions and why only the first one works? thanks in advance

+3


source to share


2 answers


Arrays.asList(myray)

returns a fixed dimensional implementation List

( java.util.Arrays.ArrayList

) backed by an array, so you cannot add elements to it (or remove elements from it).



When you create a new one java.util.ArrayList

and pass it to the constructor the fixed size List

you got from Arrays.asList

(just like in the first snippet), you get a normal java.util.ArrayList

one to which you can add elements.

+4


source


Because a method asList

from a class Arrays

returns you an immutable list in which you cannot change it. It's just readable.

here's the docs for the same

Returns a fixed-size list supported by the specified array.



Where, as in the first case, you don't use it directly and you create a new list around it.

new ArrayList<Integer>(Arrays.asList(myray));

      

When you do this internally, the items only get a copy, and you get a regular ArrayList instance.

+1


source







All Articles