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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With