[英]Can't remove all element in java.util.Map.Entry
In all element in Entry Map, I only can remove the one element at least position. 在Entry Map中的所有元素中,我至少只能删除一个元素的位置。 Can anybody explain what reason ? 谁能解释什么原因?
Ps: I think problem at EntryMap with HashMap 附:我认为EntryMap的HashMap有问题
This is full code: 这是完整的代码:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Neti {
static Map<Integer, String> mm = new HashMap<>();
static void removeEntry(Integer val) {
for (Entry<Integer, String> entry : mm.entrySet()) {
if (entry.getKey() == val) {
mm.remove(val);
break;
}
}
}
public static void main(String[] args) {
mm.put(123, "one");
mm.put(1234, "two");
mm.put(12345, "three");
mm.put(123456, "four");
Scanner scanner = new Scanner(System.in);
System.out.println("We have: " + mm);
for (;;) {
System.out.print("Number to remove: ");
int val = scanner.nextInt();
removeEntry(val);
System.out.println("Map entries are: " + mm.toString());
}
}
}
Your entire removeEntry
method can be replaced by a single statement - mm.remove(val)
. 您的整个removeEntry
方法可以由单个语句mm.remove(val)
代替。 There's no need to iterate over the entrySet
to find the key you wish to remove, and even if there was, using ==
for reference types is usually wrong. 无需遍历entrySet
即可找到要删除的键,即使存在,对引用类型使用==
通常也是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.