删除arraylist中的每个第3个元素

时间:2013-01-13 02:28:22

标签: java arrays arraylist

我试图遍历一个arraylist并逐渐删除每3个索引的元素。一旦它到达arraylist的末尾,我想将索引重置回到开头,然后再次循环遍历arraylist,再次每3个索引删除一个元素,直到arraylist中只剩下一个元素。

listOfWords是一个长度为3的数组,以前填充过。

int listIndex = 0;

do
{           
    // just to display contents of arraylist    
    System.out.println(listOfPlayers);

    for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
    {
        System.out.print("Player");
        System.out.print(listOfPlayers.get(wordIndex));
        System.out.println("");
        listIndex = wordIndex;                                  
    }           

    listOfPlayers.remove(listOfPlayers.get(listIndex)); 
}
while(listOfPlayers.size() > 1);

我试图实施几个小时但我仍然遇到麻烦。以下是arraylist的元素:

1, 2, 3, 4

1, 2, 4

1, 2

然后它在检查第三个元素(不再存在)时抛出'index out of bounds error'异常。一旦它到达最后一个元素,我希望它环绕到第一个元素并继续通过数组。我也希望它从它停止的地方开始,而不是从一开始就从arraylist中删除一个元素。

7 个答案:

答案 0 :(得分:3)

也许我刚刚错过了这艘船,但这就是你所追求的吗?

import java.util.ArrayList;
import java.util.Random;

public class Test {

    public static void main(String[] args) {

        ArrayList<Integer> numbers = new ArrayList<Integer>();
        Random r = new Random();

        //Populate array with ten random elements
        for(int i = 0 ; i < 4; i++){
            numbers.add(r.nextInt());
        }

        while(numbers.size() > 1){
            for(int i = 0; i < numbers.size();i++){
                if(i%3 == 0){//Every 3rd element should be true
                    numbers.remove(i);
                }
            }
        }
    }
}

答案 1 :(得分:1)

你可以将每个第三个元素移动到一个临时列表,然后在完成每个循环时使用List#removeAll(Collection)删除项目......直到主列表为空...

答案 2 :(得分:1)

让我们备份并以算法方式查看问题。

  • 从第一项开始,开始计算。
  • 转到下一个项目并递增计数。如果没有下一个项目,请转到开头。
  • 如果计数为“3”,则删除该项并重置计数。 (或模数。)
  • 如果列表中还有一个项目,请停止。

让我们写伪代码:

function (takes a list)
  remember what index in that list we're at
  remember whether this is the item we want to delete.

  loop until the list is size 1
    increment the item we're looking at.
    increment the delete count we're on

    should we delete?
      if so, delete!
      reset delete count

    are we at the end of the list?
      if so, reset our index

以这种方式看待它,将其立即转换为代码相当容易:

public void doIt(List<String> arrayList) {
  int index = 0;
  int count = 0;

  while(arrayList.size() != 1) {
    index = index + 1;
    count = count + 1; //increment count

    String word = arrayList.get(index);//get next item, and do stuff with it

    if (count == 3) {
      //note that the [Java API][1] allows you to remove by index
      arrayList.remove(index - 1);//otherwise you'll get an off-by-one error
      count = 0; //reset count
    }

    if (index = arrayList.size()) {
      index = 0; //reset index
    }
  } 
}

所以,你可以看到诀窍是逐步思考你正在做什么,然后慢慢将其转化为代码。我想你可能已经开始着手修复你的初始尝试:永远不要害怕抛出代码。

答案 3 :(得分:0)

你可以使用一个递增3的计数器int k,例如k += 3。但是,在将该计数器用作踢出任何数组元素的索引之前,请检查是否已超出此范围,如果是,则从计数器k中减去此数组的长度。另外,一旦发现数组中只剩下一个元素,请确保从break出来。

int k = -1;
int sz = list.length;
while (sz > 1)
{
    k += 3;
    if (k >= sz)
    {
        k -= sz;
    }
    list.remove(k);
    sz --;
}

这个例子表明你已经知道你驱逐一个元素的频率,即sz - 1次。

顺便说一句,sz % 3只有三个可能的结果,0,1,2。用一张纸和一杯咖啡,你可以找到幸存的元素将依赖于什么,而不是运行任何循环都可以!

答案 4 :(得分:0)

您可以尝试使用迭代器。这是迟到的irl,所以不要期待太多。

public removeThirdIndex( listOfWords ) {
    Iterator iterator = listOfWords.iterator
    while( iterator.hasNext() ){
        iterator.next();
        iterator.next();
        iterator.next();
        iterator.remove();
    }
}


@Test
public void tester(){
    // JUnit test > main
    List listOfWords = ... // Add a collection data structure with "words"

    while( listOfWords.size() < 3 ) {
        removeThirdIndex( listOfWords ); // collections are mutable ;(
    }

    assertTrue( listOfWords.size() < 3 );
}

答案 5 :(得分:0)

我只需将remove设置为null,然后在内循环中跳过空值。

boolean continue;
do {
   continue = false;
   for( int i = 2; i < list.length; i += 3 ){
      while( list.item(i++) == null &&  i < list.length );
      Sout("Player " + list.item(--i) );
      continue = true;
   }
} while (continue);

我选择这个而不是对阵列进行不合理的改组。

(i ++和--i可能看起来很难看,可能会被很好地重写。)

答案 6 :(得分:0)

尝试以下代码。它会继续删除nth中的每个List元素,直到剩下一个元素。

    List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    int nth = 3;
    int step = nth - 1;
    int benchmark = 0;

    while (array.size() > 1) {
        benchmark += step;
        benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
        System.out.println(benchmark);
        array.remove(array.get(benchmark));
        System.out.println(array);
    }
相关问题