how to generate unique numbers less than 8 characters long.

Posted by loudiyimo on Stack Overflow See other posts from Stack Overflow or by loudiyimo
Published on 2010-03-28T16:17:24Z Indexed on 2010/03/28 16:23 UTC
Read the original article Hit count: 242

Filed under:
|
|

hi

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 }

© Stack Overflow or respective owner

Related posts about java

Related posts about uuid