Reputation: 11
if (sList.size() > 0) {
for (int i = 0; i < tList.size(); i++) {
String a = sList.get(i).getString();
String b = tList.get(i).getString();
if (a.equals(b)) {
tList.remove(i);
}
}
}
sList.Size is 1, tList.size is 100.
However, I keep getting this error:
Exception: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I don't understand why this is, I have also tried iterators, same problem.
Upvotes: 0
Views: 146
Reputation: 3534
that's because you're looping through slist in your loop which only has 1 element in it. When i > 0 that exception will occur, obviously.
Upvotes: 1
Reputation: 120198
you are iterating over tList
which you said has size 100, but sList
only have size 1. So as soon as you get to the second item of tList
you have already exceeded the size of sList
.
Note that you can use removeAll
to remove everything in sList
from tList
. Just make sure your equals
and hashCode
methods are correct.
Upvotes: 1
Reputation: 89169
If sList.size()
is 1
then you can only get item at index 0
and not 1
, hence why you're getting
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
So, when i == 1
, you're already reading going out of bound (remember, java counts from 0
and not 1
).
Upvotes: 0
Reputation: 303
Java lists are indexed (like all other collections) are indexed from 0. A list of length 1 has only a member at position 0.
If you try to access a member that doesn't exist (which you are doing here) then you will get this exception.
Upvotes: 0
Reputation: 15892
You're not actually iterating through sList
, you're only going through tList
(line 2) and assuming sList
has the same number of elements (line 3) which it doesn't... as soon as you're done the first element (0) which is in both it's failing.
Upvotes: 0
Reputation: 272497
You are iterating for 0 to 100 (the size of tList
). You say that the size of sList
is 1, but you are trying to access sList[i]
. So you are reading out of bounds.
Upvotes: 0
Reputation: 60681
This will happen if sList contains fewer items than tList. You need a separate loop counter for iterating through the elements of sList, rather than trying to use a single counter for both.
Upvotes: 0