Вопрос

Is there a way to generate a unique surrogate string like UUID.randomUUID() but containing characters only (means no numbers)? The string is stored in multiple databases on different hosts and has to be system wide unique (even if I generate two keys at the same time - i.e. by threads).

Это было полезно?

Решение

Just wrote this - random string of upper case characters:

package dan;

import java.util.Random;

public class RandText {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String s = getRandomText(100);
        System.out.println(s);

    }


    public static String getRandomText(int len) {
        StringBuilder b = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i<len;i++) {
            char c = (char)(65+r.nextInt(25));
            b.append(c);
        }
        return b.toString();
    }
}

Другие советы

Apache Commons Lang 3 has a class named RandomStringUtils that can be used to obtain random alphabetic strings:

int stringSize = 8;  // just choose the size better suits you
String randomString = RandomStringUtils.randomAlphabetic(stringSize);

If you need this to be unique even when more than one thread is running then you will need a way to synchronize them (maybe using synchronized blocks and a while loop) and checking in that database that no previous string equal to the generated one exists.

EDIT - A rough example

Set<String> previousKeys = new HashSet<String>();

public String generateKey(int stringSize) {
    String randomString = "";
    synchronized(previousKeys) {
        do {
            randomString = RandomStringUtils.randomAlphabetic(stringSize);
        } while (randomString.length() == 0 || !previousKeys.add(randomString));
    }
    return randomString;
}

if you are looking to generate random characters, use a random int generator, and have it generate a random number 65 - 122. keep in mind that 91-96 are not A-Z or a-z in ascii, though. Keep in mind you will want to convert this int to a char.

This can be helpful: http://www.asciitable.com/

String id = UUID.randomUUID().toString().replaceAll("-", "");
id.replaceAll("0","zero");
// [...]
id.replaceAll("9","nine");

I am feeling bad about this approach.

Grab your UUID, strip out the "-"s. Convert char '1' -> 'Z', '2' -> 'Y' etc.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top