-3
List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.

alayor
  • 4,537
  • 6
  • 27
  • 47
sanjay
  • 165
  • 2
  • 12
  • For better help sooner post a valid [mcve] – Frakcool Jul 06 '17 at 19:38
  • 1
    It seems you're missing the call to `s.next()`. – alayor Jul 06 '17 at 19:39
  • 1
    What is the point of `Iterator s = list.iterator()` if you are using `list.get(i)`? Use `iterator.next()` to get current element, test its properties and depending on result decide if you want to remove it or not. Or simpler use `list.removeIf(filteringPredicate)` – Pshemo Jul 06 '17 at 19:43
  • "...decide if you want to remove it or not" BTW removal should be done via iterator, not via `list`. Otherwise you can also face ConcurrentModificationException explained in [this question](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Pshemo Jul 06 '17 at 19:55
  • #Pshemo i am sure that i want to remove a list – sanjay Jul 06 '17 at 19:59
  • @sanjay your code is not removing list, but element *from* list. Removal can be done via iterator, and should be done by it. Simply use `Studentdb student = s.next(); if (..thisStudendShouldBeRemoved..){s.remove()};`. – Pshemo Jul 06 '17 at 20:04
  • BTW on Stack Overflow to ping specific user use `@userName` not `#userName`. – Pshemo Jul 06 '17 at 20:06

3 Answers3

0

Removing items from lists in a for loop is always a mess.

It's best to place the desired items in another list, or if using Java 8 use streams and filter the list.

MaxPower
  • 881
  • 1
  • 8
  • 25
0

You're code has an infinite loop because it doesn't get the next item in the iterator.

So, by the time i is equal to 3 you're code is trying to get the 4th element in the list, which it's why you're getting this exception.

You should call the next() method in your s object.

alayor
  • 4,537
  • 6
  • 27
  • 47
0

Just include a condition such that it breaks, after reaching at the position size-1. And i hope u know very well that if the size of a list is n, the list gets indexing from 0 to n-1. In your error message, what it actually says is that, Your are trying to iterate to an item which is out of the allocated area of the list.

Goutham
  • 307
  • 2
  • 11