I am trying to produce many random strings consist of 4 digits, and they should not repeat to each other. I don't know the exact number, but around few hundreds. I tried nextInt():
public static String generateLogID() {
Random rdm = new Random();
String s = "";
for (int i=0;i<4;i++) {
String digit = String.valueOf(rdm.nextInt(9));
s = s.concat(digit);
}
return s;
}
However, when it comes around No.70 or 80, it got repeat string. Theoretically there will be 10*10*10*10 possibilities, why it repeat so soon, and what should I do to avoid repeat? Thank you for any advice!
I used HashMap to save all record to avoid repeat, and it works so well.
HashMap<Integer, String> map = new HashMap<Integer, String>();
int count = 0;
for(loop conditions){
String id = IDGenerator.generateLogID();
while(map.containsValue(id)){
id = IDGenerator.generateLogID();
}
map.put(count, id);
count++;
}
But what I really want to know is why this generator generate repeat so soon, and is there other generate method which lower the repetition rate?