UnsupportedOperationException when trying to remove a list of items from another list

6.8k views Asked by At

I have coded below, i dint know what is wrong but validDatesIterator.remove() is giving me UnsupportedOperationException exception. Using java 1.6

List<Integer> validDates = Arrays.asList(26,27,28,1,2,3,4);
    List<Integer> daysToBeRemoved = Arrays.asList(1,2); 
    Iterator<Integer> validDatesIterator = validDates.listIterator();
    while(validDatesIterator.hasNext()) {
        Integer curValue = validDatesIterator.next();
        for(Integer dayToRemove:daysToBeRemoved) {
            if(curValue.equals(dayToRemove)) {
                validDatesIterator.remove();
                break;
            }
        }
    }

Also When i debug valid dates(curValue initially it gives 27, instead 26) is starting with element 27, not 26.

May be a duplicate question, but searched a lot, dint find kinda of this. Please help.

2

There are 2 answers

0
Reimeus On BEST ANSWER

Arrays.asList returns Arrays.ArrayList, a List implementation that doesnt support the removal of elements. Use

List<Integer> validDates = new ArrayList<>(Arrays.asList(26,27,28,1,2,3,4));
0
Bohemian On

First problem: Arrays.asList() returns an (basically) unmodifiable list. Pass it to the constructor of a normal List.

Second problem: You have reinvented the wheel.

Try this:

List<Integer> validDates = new ArrayList<>(Arrays.asList(26,27,28,1,2,3,4));
List<Integer> daysToBeRemoved = Arrays.asList(1,2);

validDates.removeAll(daysToBeRemoved);