Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ch.phonon.examples.covariance.Main.copy(Main.java:79)
at ch.phonon.examples.covariance.Main.main(Main.java:108)
Jesper de Jong wrote:That happens because Arrays.asList() returns an implementation of interface List to which you cannot add any elements - the add() method of the returned List throws UnsupportedOperationException.
If you want to be able to add numbers, then copy whatever Arrays.asList() returns into a regular ArrayList:
Jesper de Jong wrote:Because Arrays.asList() returns a special List that is backed by the original array - which means that if you change an element in the original array, you'll see the change in the list returned by Arrays.asList() for that array, and vice versa.
That wouldn't be possible if Arrays.asList() returned a regular java.util.ArrayList.
It also explains why add() isn't implemented - because you cannot make an array larger after creating it, so there's no way to add an extra element to the array that's behind the List.
Not sure. It says T... array in the API documentation and there is no overloading of that method, so I think you would regard that as a 1‑element Object[] and get a List<int[]>. I do not think there is any boxing involved.Stephan Strauss wrote: . . .
How are primitive arrays handeled ... is each element boxed, probably not ... a list with one entry that is a array of int ?
. . .
Campbell Ritchie wrote: ... did it alter the original array?
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |