Reputation: 91
I am trying to use remove method but I am getting messed up as I keep getting error for this:
List<String> list1 = new ArrayList<String>();
list1.add("Apple");
list1.add("Bus");
list1.add("Cat");
list1.add("Dog");
String ne = list1.listIterator().next();
System.out.println(ne);
list1.listIterator().remove();
the remove statement throws an error?? can anyone tell me why?? same thing when I just use iterator in place of listIterator?
Upvotes: 2
Views: 143
Reputation: 521239
Your code is correct in that you are allowed to call ListIterator#remove()
once for each time next()
is called (see Javadoc). However, in your code you are actually calling remove()
on a new list iterator, not the one you used before it. Try the following code and hopefully it will be clear what you did wrong:
List<String> list1 = new ArrayList<String>();
list1.add("Apple");
list1.add("Bus");
list1.add("Cat");
list1.add("Dog");
// retain a reference to the same list iterator
ListIterator<String> list1itr = list1.listIterator();
String ne = list1itr.next();
System.out.println(ne);
list1itr.remove();
Upvotes: 3