Hi I am figuring out why this code is not working the way how i wanted it to work..
What i basically want is a random object that has a char and an int generating and putting it into an arraylist. However if the generated matches the same in the arraylist it must regenerate the number again and check to see if it exists. If it does not exist it will then be added into the arraylist.
private final char letter;
private final int num;
private static Collection<RegistrationNumber> REGISTRATION_NUMBER = new ArrayList<RegistrationNumber>();
private RegistrationNumber(){
Random rand = new Random();
this.num = (1+(rand.nextInt(3)));
this.letter = Character.toUpperCase((char)(rand.nextInt(1)+'a'));
}
public static RegistrationNumber getInstance(){
boolean foo = false;
RegistrationNumber rn = null;
while(!foo){
rn = new RegistrationNumber();
if(!REGISTRATION_NUMBER.contains(rn)){
REGISTRATION_NUMBER.add(rn);
foo=true;
}
}return rn;
}
Once I look through the arraylist, there are still some repeating for example [A1,A1,A2] or [A2,A2,A3]
Many thanks!
containsis doing internally ? Have you implemented equals forRegistrationNumber? Maybe you should use aSetinstead of aList.