简体   繁体   English

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

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

I tired to make a super basic bingo go(no need to over complicate stuff) 我厌倦了做一个超级基本的宾果游戏(不需要过度复杂的东西)

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());

is this where it goes wrong? 这是哪里出了问题? instead of removing the number eg "10", does it remove the element in position 10 in the array? 而不是删除数字(例如“ 10”),它是否删除了数组中位置10的元素?

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

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

}

} }

bingo.remove(no) calls remove(int index) , which removes the element whose index is no , not the element whose value is no . bingo.remove(no)调用remove(int index) ,该操作将删除索引为no的元素,而不是其值为no的元素。 If you want to remove the element whose value is no, you need to use remove(Object o) , which expects a reference type. 如果要删除值为no的元素,则需要使用remove(Object o) ,它需要引用类型。 For example, bingo.remove(Integer.valueOf(no)); 例如, bingo.remove(Integer.valueOf(no)); .

There are two overloaded version of remove method in arrayList. arrayList中有两个重载版本的remove方法。

Difference between two overloaded api of remove method is One that accepts Object and other which accepts primitive index parameter. remove方法的两个重载api之间的区别是, 一个接受Object, 另一个接受原始索引参数。 And you are specifying primitive value ie 10. 并且您要指定原始值,即10。

If you want to remove element with content as 10, you change the following line from: 如果要删除内容为10的元素,请更改以下行:

int no  = ...

To

Integer no  = ...

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

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