从一个List中移除重复的数据
使用迭代方法会报异常:java.util.ConcurrentModificationException
Map<String, Interger> temp = new
HashMap<String, Interger>();
for (GroupRule rule : ruleList)
{
String ruleName = rule.getName();
if (temp.get(ruleName) == null)
{
temp.put(ruleName, 1);
} else
{
ruleList.remove(rule);
}
}
temp.clear();
主要是原因是该种方法是内部调用Iterator循环的一种实现,而在Iterator循环移除对象时只能用it.remove(),而不能用list.remove(obj),否者报并发错误。这是由于AbstractList中的 modCount和expectedModCount 两个参数在list.remove(obj)之后不相等导致的。
用it.remove()的代码如下:
Map<String, GroupRule> temp = new
HashMap<String, GroupRule>();
List<GroupRule> resList =
new ArrayList<GroupRule>();
boolean hasNickName=false;
for(Iterator<GroupRule> iter = ruleList.iterator(); iter.hasNext();)
{
GroupRule rule = iter.next();
String ruleName =
rule.getName();
if (!hasNickName && "nick_name".equals(ruleName))
{
hasNickName=true;
}
if (temp.get(ruleName) == null)
{
temp.put(ruleName, rule);
} else
{
iter.remove();
}
}
temp.clear();
用for循环可以在遍历List的时候list.remove(),代码如下:
Map<String, Interger> temp = new
HashMap<String, Interger>();
int len = ruleList.size();
for (int i=0; i< len; i++ ) {
GroupRule rule =
ruleList.get(i);
String ruleName = rule.getName();
if
(temp.get(ruleName) == null) {
temp.put(ruleName, 1);
} else
{
ruleList.remove(rule);
len--;
i--;
}
}
temp.clear();