如何从中删除对象时继续迭代ArrayList

时间:2015-11-06 20:40:33

标签: java arraylist

为了尝试在Java中实现Banker的算法,我试图迭代存储多个线程的id的ArrayList。我想继续迭代这个数组,直到找到一个安全的序列(或不是)。到目前为止,我只能遍历ArrayList一次,但是如果我发现它们是我安全序列中的下一个,我需要将对象删除。

我如何以循环方式迭代遍历ArrayList(或任何其他数据结构),因为我去的时候从中删除对象?我希望我的问题很清楚,但到目前为止我的内容是: 在最好的情况下,当列表中剩余0个对象时,算法停止。

修改 我的意思是循环时尚是这样的:0,1,2,3,4,0,1,2,3,4(我还需要能够从列表中删除进程,因此迭代应该变小。)可能看起来像:注意当剩余列表中有0时,算法会停止

0,1,2,3,4

,0,2,3,4

2,3,4

2,4

4

while (it.hasNext()) {
            Integer thisOne = it.next();
            found=false;
            // this process, can be removed from the list
            // because cN = its current need
            // a = how much the process is allocated already
            // cR=bank's current resources
            // so if cN - a <= cR, we know there is no deficit
            // we can satisfy this process, and remove it from the list 
            // of needy processes

            if(noDeficit(cN[thisOne], a[thisOne], cR)){

                // we take away its resources and give them to the bank
                Utility.add(cR, a[thisOne]);
                Utility.zeroOut(cN[thisOne]);
                Utility.zeroOut(a[thisOne]);

                found = true;
                // we remove it from the list of processes 
                it.remove();                                    
            }if(!found) return false;

        }

1 个答案:

答案 0 :(得分:0)

没有真正得到你的“发现”条件应该做的事情,但这是一种方法。

    //todo  create loop condition for stopping, eg originalList.size() > 0
    //eg
    List<Integer> itemsToRemoveList = new ArrayList<Integer>();
    while (originalList.size() > 0) { 
       Iterator it = originalList.iterator();      

       while (it.hasNext()) {
          Integer thisOne = it.next();
          found=false;
          // this process, can be removed from the list
          if(noDeficit(cN[thisOne], a[thisOne], cR)){

              // we take away its resources and give them to the bank
              Utility.add(cR, a[thisOne]);
              Utility.zeroOut(cN[thisOne]);
              Utility.zeroOut(a[thisOne]);

              // we remove it from the list of processes 
              itemsToRemoveList.add(thisOne);
           }                                   
        } //end loop

        for (Integer integerToRemove : itemsToRemoveList) {  
           originalList.remove(integerToRemove);
        }
        itemsToRemoveList.clear();

   }