请教各位了啊 写了个最简单的arraylist测试List<String> test = new ArrayList<String>();
test.add("aaa");
test.add("bbb");
test.add("ccc");
test.add("ddd");
test.add("eee");Iterator it = test.iterator();
while (it.hasNext())
{
String tmp = (String)it.next();
System.out.println(tmp);
if(tmp.equals("ddd"))         //如果相等需要做处理
{
                  //........做处理,做完后需要在在list中再添加一个
test.add("fffff");
                  //需要把原来的ddd删除   这个地方报错啊
it.remove();
test.remove(it.hasNext());
}
}
System.out.println("xxxxxxxxxxx");
Iterator it1 = test.iterator();
while (it1.hasNext())
{
System.out.println(it1.next());  //希望再次输出是 aaa bbb ccc eee ffff
} 怎么用list的循环操作

解决方案 »

  1.   

    用迭代器办不到,会抛异常的。
    既然是ArrayList,用索引遍历可以办到的。
      

  2.   

    集合在用Iterator遍历的时候不能删除。
      

  3.   

    你不能使用Iterator的同时又对List进行插入、删除操作。否则Iterator就会不知道怎样的处理了
    所以要不你增加、删除都使用Iterator或者ListIteraot操作。要不就是你自己遍历
      

  4.   

    List<String> test = new ArrayList<String>();
    test.add("aaa");
    test.add("bbb");
    test.add("ccc");
    test.add("ddd");
    test.add("eee"); if(test.contains("ddd")){
    test.remove("ddd");
    test.add("fffff");
    }

    System.out.println("xxxxxxxxxxx");
    Iterator it1 = test.iterator();
    while (it1.hasNext()) {
    System.out.println(it1.next()); // 希望再次输出是 aaa bbb ccc eee ffff
    }
    以上是你要实现的功能
      

  5.   

    那我怎么循环遍历 然后找到对印的数据操作后 再添加一个呢
    楼上的
    if(test.contains("ddd")){ 
    test.remove("ddd"); 
    test.add("fffff"); 

    不符合要求 因为要对里面每一个进行处理的
      

  6.   

    再补充一下 出错的原因就是因为我加了test.add("fffff"); 
    如果不添加这句 没有问题的
    显示 aaa bbb ccc ddd eee
    然后把ddd删除后显示
    aaa bbb ccc eee
      

  7.   


    List <String> test = new ArrayList <String>();
    test.add("aaa");
    test.add("bbb");
    test.add("ccc");
    test.add("ddd");
    test.add("eee"); 
    for(int i=0;i<test.size();i++){
    String tmp = (String)test.get(i);
    if(tmp.equals("ddd")){
    test.add("fffff");
    test.remove(tmp);

    }
    System.out.println(test);
      

  8.   

    你如果需要增加数据,可以使用list.listIterator()返回的ListIterator
    里面有add方法
    但是 你增加、删除都只能使用这个ListIterator,否则会报错。
      

  9.   

    List<String> test = new ArrayList<String>();
    test.add("aaa");
    test.add("bbb");
    test.add("ccc");
    test.add("ddd");
    test.add("eee"); for (int i = 0; i < test.size(); i++) {
    String tmp = test.get(i);
    if (tmp.equals("ddd")) {
    test.remove(i);
    test.add("fffff");
    i--;
    }
    }
    System.out.print(test);
      

  10.   

    某个线程在 Collection 上进行迭代时,通常不允许另一个线性修改该 Collection。通常在这些情况下,迭代的结果是不明确的。如果检测到这种行为,一些迭代器实现(包括 JRE 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为快速失败 迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。也就是说在将集合进行Iterator的迭代时,这种操作是非安全的~ 虽然普通的List循环通过判断再删除对应索引的方式可以达到你要的效果