简体   繁体   English

通过Iterator从ArrayList中删除元素

[英]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: 我想在ArrayList查找条目并删除元素,如果找到它,我想通过Iterator最简单的方法,这是我的代码:

    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() : 但是出了点问题:我没有通过我的ArrayList<Student> school迭代,而是使用it.toString()

java.util.ArrayList$Itr@188e490
java.util.ArrayList$Itr@188e490
...

What's wrong? 怎么了?

it is a Iterator , not Student it是一个Iterator ,而不是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. 使用List remove(Object)方法。

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). 如果此列表包含指定的元素,则返回true(或等效地,如果此列表因调用而更改)。

The reason you are getting this output is because you are calling toString() method on iterator and not on the Student object. 获得此输出的原因是因为您在iterator上调用toString()方法而不是在Student对象上调用。

You can remove student from the list by using 您可以使用以下方式从列表中删除student

school.remove(student);

Also, if you want to print meaningful Student object information when you write 此外,如果要在编写时打印有意义的Student对象信息

System.out.println(student);

Override toString() method for it as System.out.println() statement would internally call toString() on student object. 覆盖toString()方法,因为System.out.println()语句将在内部调用student对象上的toString()

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 . 后两个例子假设school是一个List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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