Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Conversion To List Error [duplicate]

Tags:

java

eclipse

could someone explain to me what happens in the next 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);

The code above works fine. It converts an array to a list and then adds another element. But the following code dose not work

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

The above code gives me the following error: Exception in 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

like image 324
Micael Illos Avatar asked Aug 01 '26 00:08

Micael Illos


1 Answers

Arrays.asList(myray) returns a fixed sized List implementation (java.util.Arrays.ArrayList) backed by an array, so you can't add elements to it (or remove elements from it).

When you create a new java.util.ArrayList and pass to its constructor the fixed sized List you got from Arrays.asList (as you do in your first snippet), you get a normal java.util.ArrayList to which you can add elements.

like image 188
Eran Avatar answered Aug 03 '26 13:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!