Reputation: 107
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(//);
}
Upvotes: 0
Views: 179
Reputation: 1315
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());
Upvotes: 1
Reputation: 3223
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);
}
Upvotes: 1
Reputation: 26094
Do like this.
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
Integer s = iterator.next();
System.out.println(s);
iterator.remove();
}
Upvotes: 2
Reputation: 33019
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.
Upvotes: 2
Reputation: 11939
I would suggest using a HashSet<Integer>
which doesn't allow duplicates:
Set<Integer> set = new HashSet<Integer>();
Upvotes: 1