繁体   English   中英

Java HashMap 迭代器删除错误

[英]Java HashMap Iterator Remove Error

我有以下哈希图:

Map<String,String> studentGrades = new HashMap<>();
studentGrades.put("Tom", "A+");
studentGrades.put("Jack", "B+");

Iterator<Map.Entry<String,String>> iterator = studentGrades.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String,String> studentEntry = iterator.next();
    System.out.println(studentEntry.getKey() + " :: " + studentEntry.getValue());
    iterator.remove();
}

我认为iterator.remove(); 意味着将从HashMap删除某些内容,例如iterator.remove("Tom"); ,然后当迭代发生时,它会从 HashMap 中删除。

当有iterator.remove();时,程序编译并正确运行iterator.remove(); 但是当它是iterator.remove("Tom"); 发现错误。 编译器说

要求:无参数,发现:java.lang.String 原因:实际和形式参数列表的长度不同。

发生这种情况的任何原因或我得到了iterator.remove(); 完全错了?

根据JavaSE 7 JavaDocIteratorremove方法:

从底层集合中移除此迭代器返回的最后一个元素(可选操作)。

它从集合中删除当前元素,并且“每次调用 next() 只能调用一次”。 它针对迭代中的当前值运行并且不接受任何参数。 它也是可选的,我不确定你会从你的例子中获得什么。 没有它你应该没问题。

顺便说一句:我建议,当您迭代HashMap 时,也许您可​​以尝试 for-in 方法,例如:

public static void main(String[] args) {
    HashMap<String, String> studentGrades = new HashMap<String, String>();
    studentGrades.put("Tom", "A+");
    studentGrades.put("Jack", "B+");

    for( Map.Entry<String, String> studentEntry : studentGrades.entrySet() ){
        System.out.println(studentEntry.getKey() +" :: "+ studentEntry.getValue());
    }
}


更新(每个评论线程):顺便说一句,我试了一下,它工作正常,输出没有错误。 如果您对使用 java.util.Iterator 和 Iterator 的 next remove方法死心塌地,这应该可以工作。 为方便起见,我在剪贴簿页面中对其进行测试。

 public static void main(String[] args) { HashMap<String,String> studentGrades = new HashMap<String, String>(); studentGrades.put("Tom", "A+"); studentGrades.put("Jack", "B+"); Iterator<Map.Entry<String,String>> iterator = studentGrades.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String,String> studentEntry = iterator.next(); System.out.println(studentEntry.getKey() + " :: " + studentEntry.getValue()); iterator.remove(); } }

在不同的类/接口中有两个名为remove方法。

  1. Iteratorremove()删除返回的前一项。

  2. Collectionremove(object)从集合中删除特定对象

只有第二个有object参数。 但要注意:使用它会使迭代器失效,所以不要从同一个集合的循环中调用它,它不会工作。 对于过滤,请使用迭代器(就像您一样)及其remove()方法。

暂无
暂无

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

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