There are a number of things missing from your question. For one thing, since you haven't given us the Gum
class, I can't figure out how each new Gum()
is going to create a unique Gum
. Does Gum
have some kind of flavor
instance variable that gets initialized to a random flavor? Maybe, but you haven't given us that info. Also, as the other answer points out, using ==
to compare gums isn't going to work. Assuming that each Gum
has a flavor
, you will need to provide an equals()
method that compares the flavor
fields for equality (and a hashCode
function that returns the same hash value for any Gum
objects with the same flavor).
The problem I most wanted to point out was the flaw in your loop logic. You're going through the array of existing Gum
objects, and whenever you find a duplicate, you create a new Gum
. That won't get the job done. Suppose your array consists of flavors A, B, C, D, E. Suppose your new Gum()
generates a gum with flavor C. You go through the array, and you find that it matches pack[2]
. So you generate another Gum
--say your random Gum
generator generates a Gum
with flavor B. Now your loop won't find it, since you're still going forward through the array, and you will only be looking at D and E. So you'll end up with a duplicate in your pack.
So what do you do? One option is that whenever you find a duplicate, you generate a new Gum
and then start over at the beginning of the array. That's a pretty slow way to do things, but it will work. Some better options:
Maintain a Set
of all the Gum
's that are already in the pack. Now instead of going through the array to see if a Gum
is a duplicate, just see if the set contains it. If you use a HashSet
, you'll be able to do this test in constant time instead of searching through an array. (If you use a HashSet
, you will definitely need a working hashCode
function.)
Keep an array of all the Gum
flavors that haven't been used. If you start with 12 flavors, then the first new Gum()
will use a random number from 0 to 11, the second will use a random number from 0 to 10, the third from 0 to 9, and so on. Each time, you will use the array and the random number to choose the right flavor, then do a swap to move that flavor to the end of the array. For example, if the array starts out A,B,C,D,E,F,G,H,I,J,K,L and your random number is 4, that's flavor E, and you swap that with L to make your array A,B,C,D,L,F,G,H,I,J,K,E. The next random number only goes from 0 to 11, so it won't pick E. Whatever it does pick, you swap that with K. And so on.