- HashMap数据结构
JDK7中HashMap是数组加链表的数据结构,HashMap源码中数组transient Node<K,V>[] table,链表transient Set<Map.Entry<K,V>> entrySet。其中Node包含hash、key、value、next四个元素。
- HashMap中modCount
HashMap源码modCount成员变量的注释:The number of times this HashMap has been structurally modified,即HashMap被修改的次数。
迭代器初始化的时候就对modCount和expectedModCount进行同步。
删除报错的原因分析:
1). hashmap里维护了一个modCount变量,迭代器里维护了一个expectedModCount变量,一开始两者是一样的。
2). 每次进行hashmap.remove操作的时候就会对modCount+1,此时迭代器里的expectedModCount还是之前的值。
3). 在下一次对迭代器进行next()调用时,判断是否HashMap.this.modCount != this.expectedModCount,如果是则抛出异常。
删除示例,如下代码包括注释1.删除报错和注释2.正确删除两部分,具体如下:
public class HashMapTest {
private static HashMap<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
map.put(i, "value" + i);
}
//1.删除报错
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
if (key % 2 == 0) {
System.out.println("To delete key " + key);
map.remove(key);
System.out.println("The key " + +key + " was deleted");
}
}
//2.正确删除
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer, String> entry = it.next();
Integer key = entry.getKey();
if(key % 2 == 0){
System.out.println("To delete key " + key);
it.remove();
System.out.println("The key " + + key + " was deleted");
}
}
}
}
- HashMa如何正确遍历删除元素
正确遍历删除元素的方法是,使用迭代器提供的remove方法。
迭代器里remove了一个元素之后会对expectedModCount重新赋值,这样再次遍历的时候就不会报错了。所以正确的代码写法如:2.正确删除,直接调用迭代器的remove方法。
参考: hashmap遍历时用map.remove方法为什么会报错?
网友评论