简体   繁体   English

循环中的Arraylist

[英]Arraylist in for-loop

So I have 2 arraylists (player1List, and player2List) each of which have 26 ints in them. 所以我有2个arraylist(player1List和player2List),每个数组中有26个整数。 I run them through a for-loop comparing two numbers from each. 我通过一个for循环来比较它们中的两个数字。 If one list has a number that is bigger than the other, the smaller number gets added to the winning list. 如果一个列表的数字大于另一个列表的数字,则较小的数字将添加到中奖列表中。 However, when I run it through the for-loop at a certain point I get an "indexOutOfBoundsException: Index 21: Size 21." 但是,当我在某个点通过for循环运行它时,会得到“ indexOutOfBoundsException:Index 21:Size 21”。 How do I get to run through the loop until one of the arraylists is empty? 我如何遍历循环,直到arraylists之一为空? Here is my code. 这是我的代码。

    for (int i = 0; i < player1List.size; i++){
        if (player1List.get(i) < player2List.get(i)){
            System.out.printf("Player 1: %d\n", player1List.get(i));
            System.out.printf("Player 2: %d\n", player2List.get(i));
            System.out.printf("Player 2 wins round!\n");
            player2List.add(player1List.get(i));
            player1List.remove(player1List.get(i));
        }
        if (player1List.get(i) > player2List.get(i)){
            System.out.printf("Player 1: %d\n", player1List.get(i));
            System.out.printf("Player 2: %d\n", player2List.get(i));
            System.out.printf("Player 1 wins round!\n");
            player1List.add(player2List.get(i));
            player2List.remove(player2List.get(i));
        }
        if (player1List.get(i) == player2List.get(i)){

            System.out.printf("Player 1: %d\n", player1List.get(i));
            System.out.printf("Player 2: %d\n", player2List.get(i));
            System.out.printf("It's a tie, cards return to your deck.\n");

        }
        if (player1List.isEmpty()){
        System.out.printf("Player 2 wins the game.\n");
        break;
        }
        if (player2List.isEmpty()){
        System.out.printf("Player1 wins the game.\n");
        break;
        }
        }

I have asked a similar question to this, however, this is more narrowed down to what I need. 我已经问过类似的问题,但是,这个范围更窄了我需要的范围。

If you need intermediate additions to the collection to matter in the next iteration, then you need to make sure your indexes are correct. 如果您需要中间添加到集合中的下一次迭代关系,那么你需要确保你的指标是否正确。 Hold two counters. 持有两个柜台。 When removing - do not increment. 拆卸时-请勿增加。 Check if the list is not bigger than the current index. 检查列表是否不大于当前索引。

As you can see - removing and adding while iterating makes things more complex when indexes are concerned. 如您所见-当涉及索引时,在迭代时删除和添加会使事情变得更加复杂。 That's why a better solution would be to use iterators: 这就是为什么更好的解决方案是使用迭代器的原因:

Iterator<Foo> it1 = list1.iterator();
Iterator<Foo> it2 = list2.iterator();

while(it1.hasNext() && it2.hasNext()) {
   Foo foo1 = it1.next();
   Foo foo2 = it2.next();
   if (..) {
       it2.remove();
   }
}

When you need to add to one of the collections, add to a new collection instead, that does not interfere in the iteration. 当您需要添加到一个集合中时,改为添加到一个新集合中,这不会干扰迭代。

int size = list2.size()>list1.size()?list1.size():list2.size();
for(int i=0; i<size;i++){
   ...//do all your work here.

  size = list2.size()>list1.size()?list1.size():list2.size();//last line in loop
}

because you are modifying your lists (ie removing elements), you should continuously check your limit; 因为您正在修改列表(即删除元素),所以您应不断检查您的限制; hence the last line in the loop. 因此,循环中的最后一行。

Here we go: 开始了:

ArrayList<Integer> a = new ArrayList<Integer>(
    Arrays.asList(new Integer[]{0, 1, 5}));
ArrayList<Integer> b = new ArrayList<Integer>(
    Arrays.asList(new Integer[]{3, 4, 2}));

int sA = a.size();
int sB = b.size();

for (int i = 0, j = 0; i < sA && j < sB; i++, j++) {
  int iA = a.get(i);
  int iB = b.get(j);

  if (iA < iB) {
    b.add(iA);
    a.remove(i--);
    sA--;

  } else if (iA > iB) {
    a.add(iB);
    b.remove(j--);
    sB--;
  }
}

System.out.println("a: " + a);
System.out.println("b: " + b);

Output: 输出:

a: [5, 2]
b: [3, 4, 0, 1]

Suppose there are N1 items in the first list and N2 items in the second list, the number of iterations will always be limited to the lesser of N1 and N2 . 假设第一个列表中有N1个项目,第二个列表中有N2项目,则迭代次数将始终限于N1N2的较小者。 eg if N1 is 10 and N2 is 11, there will be at most 10 iterations. 例如,如果N1为10且N2为11,则最多会有10次迭代。

When an item is transferred from one list to the other, we decrement the index counter as well as the total number of items we need to look at for the list from which the item was just removed; 当一个项目从一个列表转移到另一个列表时,我们将减少索引计数器以及我们要查找刚从中删除该项目的列表所需的项目总数; we don't care about the list to which the item was added, because it's always added at the end and we'll never get that far in the loop. 我们不在乎添加项目的列表,因为它总是添加在末尾,而且我们永远也不会在循环中走得那么远。

Comparisons are between corresponding items in the original lists before they are modified. 修改之前,先对原始列表中的相应项目进行比较。 In the above example, 5 is compared with 2, even though 5 is at the index 0 in the first list and 2 is at the index 2 in the second list by the time the comparison is actually done. 在上面的示例中,即使在第一个列表中的索引0处有5且在第二个列表的索引2处有2时,也将5与2进行了比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM