ArrayList contains

I don't really understand what's happening, if someone could explain this to me that would be great.

So, here's my code:

public static ArrayList<Integer> numbers = new ArrayList<Integer>();

public static void main(String[] args){
    for(int i =0; i != 90; i++){
        System.out.println(generate());
    }
}

public static int generate(){
    Random random = new Random();
    int rand = random.nextInt(89)+1;

    while(numbers.contains(rand)){ //<---Here seems to be my problem
        rand = random.nextInt(89)+1;
        System.out.println("Number: " + rand + " already exists!");
    }
    numbers.add(rand);
    return rand;
}

I am writing a program that generates a random number from 0-90, each of which are different to the last. Unfortunately, it seems that the while loop only returns true.

Jon Skeet
people
quotationmark

You're picking from 89 random numbers (1-89 inclusive) and trying to find a unique number each time... but you're calling that 90 times. What do you expect the last iteration to do? (To put it another way - you're trying to squeeze 90 numbers into 89 slots. That's not going to work.) On the last iteration, all the possible values will already be in the list, so the condition of your while loop will always be met, whatever value is randomly chosen on each iteration.

If you wanted the numbers to be between 1 and 90 inclusive, you should be using random.nextInt(90) + 1. The argument to nextInt is the maximum number exclusive to generate - so if you call random.nextInt(3) for example, it will generate 0, 1 or 2.

(There are better ways of doing this, by the way - such as populating the list and then using Collections.shuffle - but I've concentrated on explaining the behaviour of your current code.)

people

See more on this question at Stackoverflow