Im trying to get the similar items in an arraylist through the use of iterators. I keep running into this error:
Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(ArrayList.java:872)
at com.fryslan.updater.wrappers.MethodDataItem.getIntListSimilarities(MethodDataItem.java:97)
at com.fryslan.updater.wrappers.MethodDataItem.matchAbstractNodes(MethodDataItem.java:67)
at com.fryslan.updater.wrappers.MethodDataItem.equals(MethodDataItem.java:182)
at com.fryslan.updater.Updater.<init>(Updater.java:57)
at com.fryslan.updater.Updater.main(Updater.java:99)
The code I'm using is this:
private ArrayList<Integer> getIntListSimilarities(ArrayList<Integer> base, ArrayList<Integer> target) {
ArrayList<Integer> matching = new ArrayList<>();
Iterator baseIterator = base.listIterator();
Iterator targetIterator = target.listIterator();
while (baseIterator.hasNext()) {
while (targetIterator.hasNext()) {
int bv = (int) baseIterator.next();
int tv = (int) targetIterator.next();
if (bv == tv) {
matching.add(bv);
baseIterator.remove();
targetIterator.remove();
baseIterator = base.listIterator();
targetIterator = target.listIterator();
}
}
}
return matching;
}
Your code has many problems. For instance, if the inputs are [1] and [1,2], it will throw a NoSuchElementException
:
baseIterator.remove(); // remove the element from ArrayList<Integer> base
...
baseIterator = base.listIterator(); // new Iterator from the base that had its element removed
...
while (targetIterator.hasNext()); // looking at the 2nd Integer in [1,2]
...
int bv = (int) baseIterator.next(); // NoSuchElementException
Also, your code might go into an infinite loop if base
has more elements than target
(first loop is always true
and second one is always false
when looking at base
's last element).
Here, the IllegalStateException
might be because you are calling remove
on an empty ArrayList
, however I could not reproduce the problem.
If you can't fix your codes with this hint, I'll add a solution.
Hint: Merge your two loops into one, evaluate the 2 conditions hasNext
at the same time in a single while
loop.