繁体   English   中英

从数组列表中删除元素不起作用,是否发生重复?(基本宾果游戏)

[英]Removing element from Array-list not working, duplicates happening?(basic bingo game)

我厌倦了做一个超级基本的宾果游戏(不需要过度复杂的东西)

package bingo;

 import java.util.*;

public class Bingo {

public static void main(String[] args) {

    Random rn = new Random();
    ArrayList bingo = new ArrayList();
    final int MAX = 50;
    int no  = rn.nextInt(49);
    boolean finished = false;

    for(int i = 0; i < MAX; i++){
        bingo.add(i);
    }


    while(!finished){
       // Keep the number it can generate the same size as the array-list
        no  = rn.nextInt(bingo.size());

这是哪里出了问题? 而不是删除数字(例如“ 10”),它是否删除了数组中位置10的元素?

  if(bingo.contains(no)){
            System.out.println(no);
            bingo.remove(no);
        }

        if(bingo.isEmpty()){
            finished = true;
        }
    }

}

}

bingo.remove(no)调用remove(int index) ,该操作将删除索引为no的元素,而不是其值为no的元素。 如果要删除值为no的元素,则需要使用remove(Object o) ,它需要引用类型。 例如, bingo.remove(Integer.valueOf(no));

arrayList中有两个重载版本的remove方法。

remove方法的两个重载api之间的区别是, 一个接受Object, 另一个接受原始索引参数。 并且您要指定原始值,即10。

如果要删除内容为10的元素,请更改以下行:

int no  = ...

Integer no  = ...

暂无
暂无

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

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