简体   繁体   English

从Arraylist中删除整数

[英]Removing Integer from Arraylist

I'm trying to rid of duplicates for my Bingo Program so I created an ArrayList and I want to remove the integer that is printed out in the loop. 我试图消除我的Bingo程序的重复项,所以我创建了一个ArrayList,我想删除循环中打印出的整数。 I think the loop I'm using is wrong but I'm not sure. 我认为我使用的循环是错误的,但我不确定。

             List<Integer> list = new ArrayList<Integer>();
                for(int i = 1; i <= 75; i++){
                    list.add(i);
                }

                for (Integer s : list) {
                    Collections.shuffle(list);
                    System.out.println(s);
                    list.remove(//);
                }

If you're removing all the integers, it would be a lot easier to just do this: 如果要删除所有整数,只需执行以下操作会容易得多:

Collections.shuffle(list);
for (Integer s : list) {
    System.out.println(s);
}
list = new ArrayList<Integer>();

Or, if you really want to keep the same list instance: 或者,如果您确实想保留相同的列表实例:

Collections.shuffle(list);
for (Integer s : list) {
    System.out.println(s);
}
list.clear();

Just creating a new array list is more efficient because it allows the garbage collector to just collect the entire old list, rather than removing the entries one by one. 仅创建一个新的数组列表会更有效,因为它允许垃圾收集器仅收集整个旧列表,而不是一个一个地删除条目。 If you have multiple references to the same instance, however, then you'd need to actually clear the list instead. 但是,如果您对同一实例有多个引用,则实际上需要清除该列表。

Also note that the shuffle call has been moved outside the loop. 另请注意, shuffle调用已移至循环之外。 Once you've done one shuffle, the list is already randomized, so shuffling again is kind of pointless... If you really want a "better" shuffle, you could do something like call shuffle 7 times before the first loop. 一旦完成一次随机播放,列表就已经是随机的,因此再次随机播放是没有意义的...如果您确实想要“更好的”随机播放,则可以在第一个循环之前执行7次调用shuffle

Do like this. 这样吧

for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
      Integer s = iterator.next();
      System.out.println(s);
      iterator.remove();
 }

我建议使用不允许重复的HashSet<Integer>

Set<Integer> set = new HashSet<Integer>();

Are you sure this is not what you need? 您确定这不是您所需要的吗?

private static final int NUM_BALLS = 75;

List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= NUM_BALLS; i++){
    list.add(i);
}

Collections.shuffle(list);

while (!list.isEmpty()) {
    Integer s = list.remove(list.size() - 1); // for better performance as noted by @Holger
    System.out.println(s);
}

use following code 使用以下代码

    Random generate = new Random();
    Set<Integer> set = new HashSet<Integer>();
    for(int i = 1; i <= 75; i++){
       set.add(generate.nextInt(75));
    }
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
        iterator.remove();
    }
    System.out.print(set.size());

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

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