views:

1467

answers:

7

Hi everyone,

I have an object called Student, and it has studentName, studentId, studentAddress, etc. For the studentId, i have to generate random string consist of seven numeric charaters, eg.

studentId = getRandomId();
studentId = "1234567" <-- from the random generator.

and i have to make sure that there is no duplicate id.

thanks in advance

+3  A: 

See THIS post

thelost
+7  A: 

Generating a random string of characters is easy - just use java.util.Random and a string containing all the characters you want to be available, e.g.

public static String generateString(Random rng, String characters, int length)
{
    char[] text = new char[length];
    for (int i = 0; i < length; i++)
    {
        text[i] = characters.charAt(rng.nextInt(characters.length()));
    }
    return new String(text);
}

Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.

Jon Skeet
the method require String characters, how do i specify this characters?String characters = "123456789"; ???
chandra wibowo
@chandra: Yes, exactly. Give it a string of the characters you want to select from. So if you only wanted digits you'd pass in "0123456789". If you wanted only capital letters you'd pass in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" etc.
Jon Skeet
+1  A: 

The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.

Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).

Hope this helps.

Chris Henry
yes it has to be random, that is what my project specification said
chandra wibowo
+5  A: 

This is very nice: http://commons.apache.org/lang/api-release/org/apache/commons/lang/RandomStringUtils.html

If you want uniqueness (with high probability) consider using MD5 or SHA hashes.

David Soroko
A: 

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

thanks.

Paarth
A: 

Many possibilities...

You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)

It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)

Sebastien Lorber
ya its just for a school project so i dont need to concern about security and stuff, but UUID produce 32char String, all i need is 7..ow i just got an idea, is it possible to take only the 7 first char from 32?
chandra wibowo
Using substring... what i said :)
Sebastien Lorber
+1  A: 

I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.

public class RandomNumberGenerator {

private static final Set<String> generatedNumbers = new HashSet<String>();

public RandomNumberGenerator() {
}

public static void main(String[] args) {
    final int maxLength = 7;
    final int maxTry = 10;

    for (int i = 0; i < 10; i++) {
        System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
    }
}

public static String getRandomId(final int maxLength, final int maxTry) {
    final Random random = new Random(System.nanoTime());
    final int max = (int) Math.pow(10, maxLength);
    final int maxMin = (int) Math.pow(10, maxLength-1);
    int i = 0;
    boolean unique = false;
    int randomId = -1;
    while (i < maxTry) {
        randomId = random.nextInt(max - maxMin - 1) + maxMin;

        synchronized (generatedNumbers) {
            if (generatedNumbers.contains(randomId) == false) {
                unique = true;
                break;
            }
        }
        i++;
    }
    if (unique == false) {
        throw new RuntimeException("Cannot generate unique id!");
    }

    synchronized (generatedNumbers) {
        generatedNumbers.add(String.valueOf(randomId));
    }

    return String.valueOf(randomId);
}

}