Search code examples
javalistenumsenumeration

Enum List Removal Issue


Can anyone help me to get the issue ?

public static void main(String[] args) 
{
    List<TestEnum> list1 = new ArrayList<TestEnum>();
    list1.add(TestEnum.ONE);
    list1.add(TestEnum.TWO);
    list1.add(TestEnum.THREE);

    System.out.println(list1);
    System.out.println(list1.remove(TestEnum.TWO));
    System.out.println(list1);

    System.out.println("-----------------------");

    TestEnum[] xx = new TestEnum[]{TestEnum.ONE, TestEnum.TWO, TestEnum.THREE};
    List<TestEnum> list2 = Arrays.asList(xx);

    System.out.println(list2);
    System.out.println(list2.remove(TestEnum.TWO));
    System.out.println(list2);
}

Below is the Result -

[ONE, TWO, THREE]
true
[ONE, THREE]
-----------------------
[ONE, TWO, THREE]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at java.util.AbstractCollection.remove(Unknown Source)
at Test.main(Test.java:24)

Please help - Why this is happening, I have also checked hashcode ?


Solution

  • List returned by Arrays.asList() has fixed size--the size of array it is backed by. It doesn't support operations that may lead to size change: add(), addAll(), remove(), removeAll(), retainAll(), clear().

    You may use the following idiom to create a list of modifiable size:

    List<TestEnum> = new ArrayList<>(Arrays.asList(xx));
    

    this will create an ordinary ArrayList initialized by elements copied from result of Arrays.asList().