I have a problem with random and arrays. I have a list empty list and I want to add 8 some random values, but I don’t want to some values was the same. To get some random value I use this code:
for (int i = 0; i < 8; i++) {
round = random.nextInt(31);
while (temp.get(round).equals(mix)) {
round = random.nextInt(31);
}
mix.add(temp.get(round));
}
temp is list with 32 objects and mix is my list where I want to add 8 random values. But when I random some values sometimes I get the same values. How I can get random values but without duplicates?
While others have described ways to implement a new solution, I think yours can be fixed by changing a single line:
I guess the condition is supposed to check whether the element of
tempat positionroundis already inmix. This should do:The problem with the first line is that
equalsis defined to compare an object to any other kind of object, and thus compares an element oftemp, which is probably not a collection itself, tomix, which is. Thus, the condition is always false.Collection.containsis the method to use, and you need to use the one ofmix. (As others have also pointed out, aSetis best suited to a case wherecontainsis applied often, but for 8 cases, as you need, it does not matter much whethermixis aListinstead).[edit]: By the way: since the upper bound in
random.nextInt(int)is excluded, you should only ever get the final element of 32-sizetempin yourmixif you usenextInt(32).