I know, that there is better and easier way to write removeCats method, but I'm just wondering, why my version does not work. The error tells about noSuchElementException so it seems that comparing objects returning false in every case. I tried also with '==' but it didn't work as well. Thanks for help.
public static void removeCats(Set<Object> pets, Set<Cat> cats) {
//write your code here
Iterator<Object> iterator = pets.iterator();
while(iterator.hasNext()) {
for (Cat cat : cats) {
if (iterator.next.equals(cat)) pets.remove(iterator.next());
}
}
}
Object comparison
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Zdzisław Wiertara
15 August 2019, 17:29
Your version is not working because iterator.next() is moving your iterator one element forward and it is not what you probably want.
You have two of these in for loop so with every cat u are moving your iterator 2 elements forward until there is no pets left in your iterator. You want to get current value from iterator instead of the value of next element so use iterator.current() instead.
0