简体   繁体   中英

Removing element from ArrayList through Iterator

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

The reason you are getting this output is because you are calling toString() method on iterator and not on the Student object.

You can remove student from the list by using

school.remove(student);

Also, if you want to print meaningful Student object information when you write

System.out.println(student);

Override toString() method for it as System.out.println() statement would internally call toString() on student object.

public String toString() {
    return "Student [id=" + id + ", firstName=" + firstName
            + ", lastName=" + lastName + "]";
}
for (Iterator<Student> it = school.iterator(); it.hasNext();){
    **Student st** = it.next();
    if (**st**.equals(studentToCompare)){
        it.remove();
        return true;
    }
    System.out.println(**st**.toString());
}

OR

school.remove(school.indexOf(studentToCompare));

OR

school.remove(studentToCompare);

The latter two examples assume school is a List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM