I want to make a look up for entry in ArrayList
and remove element if it's found, the simplest way I guess is through Iterator
, here's my code:
for (Iterator<Student> it = school.iterator(); it.hasNext();){
if (it.equals(studentToCompare)){
it.remove();
return true;
}
System.out.println(it.toString());
it.next();
}
But something is wrong: instead of iterating through my ArrayList<Student> school
I get using it.toString()
:
java.util.ArrayList$Itr@188e490
java.util.ArrayList$Itr@188e490
...
What's wrong?
it
is a Iterator
, not Student
for (Iterator<Student> it = school.iterator(); it.hasNext();){
Student student = it.next();
if (student.equals(studentToCompare)){
it.remove();
return true;
}
System.out.println(student.toString());
}
Why not ?
school.remove(studentToCompare);
Use List remove(Object) method.
Removes the first occurrence of the specified element from this list, if it is present (optional operation).
And moreover
It Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With