0

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Pat
  • 535
  • 1
  • 16
  • 41
  • possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – Raedwald Jun 18 '15 at 11:44
  • Can you use List#removeAll? – MadProgrammer Jun 18 '15 at 11:45

2 Answers2

1

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));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

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);
Bohemian
  • 412,405
  • 93
  • 575
  • 722