I want to generate unique id’s everytime i call methode generateCustumerId(). The generated id must be 8 characters long or less than 8 characters.
This requirement is necessary because I need to store it in a data file and schema is determined to be 8 characters long for this id.
Option 1 works fine. Instead of option 1, I want to use UUID. The problem is that UUID generates an id which has to many characters. Does someone know how to generate a unique id which is less then 99999999?
option 1
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class CustomerIdGenerator {
private static Set<String> customerIds = new HashSet<String>();
private static Random random = new Random();
// XXX: replace with java.util.UUID
public static String generateCustumerId() {
String customerId = null;
while (customerId == null || customerIds.contains(customerId)) {
customerId = String.valueOf(random.nextInt(89999999) + 10000000);
}
customerIds.add(customerId);
return customerId;
}
}
option2 generates an unique id which is too long
public static String generateCustumerId() {
String ownerId = UUID.randomUUID().toString();
System.out.println("ownerId " + ownerId);
return ownerId
}
Does it need to be unique or random? If it only needs to be unique, you could load the highest value from the datastore when the application is launched (assuming only one app is writing to the data file). One you have your highest value:
Depending on what characters you allow in you uuid this can be done various ways. I would read the last character of the current String, check if it’s the last allowed character. Is so, increment the 7th character and so on. Else, increment the last character.