62,614
社区成员
发帖
与我相关
我的任务
分享
for(int i=0;i<map.size();i++){
Object key = createNewKey();
Object val = createValue();
map.put(key,val);
}
上述代码中,在遍历Map内容时,由于新增了键值对造成遍历过程中size返回的数值不一致,
从而产生不可预期的结果。这时,要采用迭代器来完成增删操作。
*If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
也就是说当你调用values时,会形成collection与map的value、值建立映射,相互影响,
而且这里只支持通过Iterator的删除,不支持添加。
这样的话当进行多线程操作时,间接调用size就能保证获取的size是正确的结果。
而直接调用size,当遍历时是支持add的,这样可能会造成结果的不准确!
以上仅是个人见解,如有不正,希望指正!谢谢!