原因:在很多时候,我们使用map的时候,需要对它进行过滤,那么该怎样做呢?
尝试1:
public
class ModifyMap
{
public static Map<Integer, String> createMap()
{
Map<Integer, String> map = new HashMap<Integer, String>();
addElementToMap(map);
return map;
}
public static void addElementToMap(Map<Integer, String> map)
{
if(map == null)
{
return;
}
for( int i = 0; i < 10; i++)
{
map.put(i, String.valueOf(i));
}
}
/**
* 判断是否为奇数(偶数:even)
*/
public static boolean isOdd( int num)
{
if(num % 2 != 0)
{
return true;
}
return false;
}
public static void main(String[] args)
{
Map<Integer, String> map = createMap();
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext())
{
int key = it.next();
if(isOdd(key))
{
{
public static Map<Integer, String> createMap()
{
Map<Integer, String> map = new HashMap<Integer, String>();
addElementToMap(map);
return map;
}
public static void addElementToMap(Map<Integer, String> map)
{
if(map == null)
{
return;
}
for( int i = 0; i < 10; i++)
{
map.put(i, String.valueOf(i));
}
}
/**
* 判断是否为奇数(偶数:even)
*/
public static boolean isOdd( int num)
{
if(num % 2 != 0)
{
return true;
}
return false;
}
public static void main(String[] args)
{
Map<Integer, String> map = createMap();
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext())
{
int key = it.next();
if(isOdd(key))
{
map.remove(key);
}
}
System.out.println(map.toString());
}
}
}
}
System.out.println(map.toString());
}
}
但是在执行map.remove(key);这一行的时候,将会报Exception in thread "main" java.util.ConcurrentModificationException
原因:如果进行迭代时用调用此方法之外【Iterator.remove()】的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。
将红线部分改为it.remove()就ok了
但是很遗憾,Iterator好像只提供了remove方法,像添加和修改好像就不行了,有没有在遍历的时候能够进行修改和添加的好方法呢?如果是通过复制一个集合存放的话老感觉效率比较低
转载于:https://blog.51cto.com/eric1314/1136523