NGix
NGix

Reputation: 2662

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?

Upvotes: 5

Views: 24769

Answers (4)

Suresh Atta
Suresh Atta

Reputation: 122026

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

Upvotes: 14

Prasad Kharkar
Prasad Kharkar

Reputation: 13566

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 + "]";
}

Upvotes: 1

T-Bull
T-Bull

Reputation: 2146

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.

Upvotes: 1

johnchen902
johnchen902

Reputation: 9609

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());
}

Upvotes: 22

Related Questions