简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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