Arrays.asList returned List - Its modifying/write-through semantics (original) (raw)
Jaikiran Pai jai.forums2013 at gmail.com
Wed Aug 15 05:58:54 UTC 2018
- Previous message: JDK 12 RFR of 5075463 : (enum) Serialized Form javadoc for java.lang.Enum is misleading
- Next message: Arrays.asList returned List - Its modifying/write-through semantics
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Consider the following code:
import java.util.Arrays; import java.util.List;
public class ArraysAsListTest {
public static void main(final String[] args) throws Exception { final List someList = Arrays.asList(new String[] {"a"}); System.out.println("Removed? " + someList.remove("a")); } }
It uses Arrays.asList to create a java.util.List and then calls a list.remove(...) on it. This currently runs intothe following exception:
Exception in thread "main" java.lang.UnsupportedOperationException: remove at java.base/java.util.Iterator.remove(Iterator.java:102) at java.base/java.util.AbstractCollection.remove(AbstractCollection.java:299) at ArraysAsListTest.main(ArraysAsListTest.java:8)
The javadoc of Arrays.asList[1] states the following:
"Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)..."
and has no other mention of how it's supposed to behave with "write" operations. Given that the javadoc states that the returned list is "write through", would that mean a "add/removal" is allowed? Probably not, because it does say it's a fixed size list.So the size altering, write operations (like add(), remove()) aren't allowed, but that isn't clear from the javadoc. So should the javadoc be updated to clarify the semantics of what changes are "write through" and what changes are not supported?
Furthermore, the UnsupportedOperationException isn't always thrown from such a returned list. Consider this minor modification to the above code:
final List someList = Arrays.asList(new String[] {"a"}); System.out.println("Removed? " + someList.remove("b"));
I add "a" and remove "b". This now runs fine without exceptions and prints "Removed? false". Should the implementation just throw the UnsupportedOperationException irrespective of whether or not the element is contained insuch a returned list? If not, should that be made clear in the javadoc (maybe same for addoperations)?
[1] https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html#asList(T...)
-Jaikiran
- Previous message: JDK 12 RFR of 5075463 : (enum) Serialized Form javadoc for java.lang.Enum is misleading
- Next message: Arrays.asList returned List - Its modifying/write-through semantics
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]