使用迭代器来对集合进行去重
迭代器里面的迭代器不能使用remove()方法,因为外层迭代器的hasnext()和next()存储了下一个对象地址,而如果你在内层迭代器删除了这个地址,就会产生hasnext()方法返回ture,而next()方法根据地址却找不到对象的存在而产生错误。
下面是使用迭代器的嵌套对集合进行去重:
public static void checkRepeat(ArrayList<Integer> list){
//计数器 ---- 计重复的对象有几个
int count=0;
//外层迭代器
Iterator<Integer> it2 = list.iterator();
while(it2.hasNext()){
Integer integer=it2.next();
//内层迭代器
Iterator<Integer> it3 = list.iterator();
//定义重复次数,如果重复次数达到2次,即视为重复
int count2=0;
while(it3.hasNext()){
Integer integer1=it3.next();
//重复一次 计数器+1
if(integer==integer1){
count2++;
}
}
//因为自己和自己也比一次,所以重复次数达到2次,才视为重复
if(count2>=2){
//重复对象计数器+1
count++;
System.out.println("...即将删除"+integer+"---------第"+count+"个重复元素");
//删除对象
it2.remove();
}
}
}