Java中hashmap的删除和大小陷阱?
如代码所示: 我不明白为什么在第一个映射中,大小是100(在remove()之后),但在第二个映射中,大小是1而不是2。这是因为hashmap中存储的数据类型与hashmap中存储的数据类型不同吗
public class test {
public static void main(String[] args) {
Map<Short, String> map = new HashMap<Short, String>();
for (short i = 0; i < 100; i++) {
map.put(i, String.valueOf(i));
map.remove(i - 1);
}
Map<Integer, Integer> hashmap = new HashMap<>();
hashmap.put(3,4);
hashmap.put(4,5);
hashmap.remove(3);
System.out.println(hashmap.size());
System.out.println(map.size());
}
}
救救我
# 1 楼答案
i-1
是int
表达式,即使i
是short
这意味着您实际上调用了
map.remove(Integer.valueOf(i - 1))
Integer
对象永远不等于Short
对象,即使它们具有相同的值,因此remove
调用将失败(即不删除任何内容)相反,您应该编写
map.remove((short) (i-1));
为什么
map.remove()
甚至接受不属于键类型的对象是a different question