Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing element from ArrayList through Iterator

Tags:

java

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?

like image 742
NGix Avatar asked Jun 15 '13 11:06

NGix


2 Answers

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());
}
like image 103
johnchen902 Avatar answered Nov 15 '22 04:11

johnchen902


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).

like image 36
Suresh Atta Avatar answered Nov 15 '22 04:11

Suresh Atta