Why does the following java code result in an infinite loop?
import java.util.LinkedList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int n = 3;
Random rand = new Random();
LinkedList<Integer> fields = new LinkedList<Integer>();
for (int i = 0; i < n*n; i++) {
fields.add(i);
}
while (fields.size() > 0) {
// Choose Field
int f = rand.nextInt(fields.size());
fields.remove((Integer) f);
System.out.println(fields.size());
}
}
}
The way you use
remove, you remove objects by value, not by position.Say your list consists of values
[0, 1, 2, 3], and you remove0and1the first two times. Now you have[2, 3], whose size is 2, so you will never remove3now!To remove by position rather than value, say
fields.remove(f). (Notice thatfis an integer, while(Integer)fis an object of the type contained in the list container.)(Alternatively, for different behaviour, you could continue removing by value, but you should now draw the random number from the range
[min, max], where you have to determine the extremal values of the list elements separately. This may take a lot longer, of course, since you will have a lot of “misses” where you don’t remove anything.)