如何在Java中生成随机字符串[重复]

时间:2022-03-14 16:47:50

This question already has an answer here:

这个问题在这里已有答案:

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.

我有一个名为Student的对象,它有studentName,studentId,studentAddress等。对于studentId,我必须生成由七个数字字符组成的随机字符串,例如。

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

And I have to make sure that there is no duplicate id.

我必须确保没有重复的ID。

7 个解决方案

#1


127  

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.

生成随机字符串很简单 - 只需使用java.util.Random和包含您想要的所有字符的字符串,例如:

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.

现在,为了获得唯一性,您需要将生成的字符串存储在某处。你如何做到这将取决于你的应用程序的其余部分。

#2


52  

This is very nice:

这非常好:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html

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

如果您想要唯一性(很有可能),请考虑使用MD5或SHA哈希值。

#3


17  

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

您还可以使用java.util包中的UUID类,该类返回32位字符String的随机uuid。

java.util.UUID.randomUUID().toString()

java.util.UUID.randomUUID()。的toString()

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

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

#4


5  

Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";

for (int i=0; i<=top; i++) {
  data = (char)(ran.nextInt(25)+97);
  dat = data + dat;
}

System.out.println(dat);

#5


2  

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.

我认为以下类代码可以帮助您。它支持多线程,但你可以做一些改进,比如删除同步块和同步到getRandomId()方法。

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);
}

}

#6


1  

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

您需要问的第一个问题是您是否真的需要ID是随机的。有时,顺序ID就足够了。

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?).

现在,如果您确实需要它是随机的,我们首先注意到生成的不包含重复项的数字序列不能被称为随机数。 :p现在我们已经解决了这个问题,最快的方法是使用包含已生成的所有ID的Hashtable或HashMap。每当生成新ID时,请根据哈希表对其进行检查,如果ID已经出现则重新生成。如果学生人数远远少于身份证的范围,这通常会很有效。如果不是,则由于需要重新生成ID的概率增加,您将陷入更深的麻烦,P(生成新ID)= number_of_id_already_generated / number_of_all_possible_ids。在这种情况下,请检查第一段(您是否需要ID是随机的?)。

Hope this helps.

希望这可以帮助。

#7


1  

Many possibilities...

很多可能......

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

你知道如何随机生成一个整数吗?你可以从中生成一个char ...(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 :)

这取决于你需要什么,随机性的水平,所涉及的安全性......但是对于一个学校项目,我想让UUID子串适合:)

#1


127  

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.

生成随机字符串很简单 - 只需使用java.util.Random和包含您想要的所有字符的字符串,例如:

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.

现在,为了获得唯一性,您需要将生成的字符串存储在某处。你如何做到这将取决于你的应用程序的其余部分。

#2


52  

This is very nice:

这非常好:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html

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

如果您想要唯一性(很有可能),请考虑使用MD5或SHA哈希值。

#3


17  

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

您还可以使用java.util包中的UUID类,该类返回32位字符String的随机uuid。

java.util.UUID.randomUUID().toString()

java.util.UUID.randomUUID()。的toString()

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

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

#4


5  

Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";

for (int i=0; i<=top; i++) {
  data = (char)(ran.nextInt(25)+97);
  dat = data + dat;
}

System.out.println(dat);

#5


2  

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.

我认为以下类代码可以帮助您。它支持多线程,但你可以做一些改进,比如删除同步块和同步到getRandomId()方法。

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);
}

}

#6


1  

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

您需要问的第一个问题是您是否真的需要ID是随机的。有时,顺序ID就足够了。

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?).

现在,如果您确实需要它是随机的,我们首先注意到生成的不包含重复项的数字序列不能被称为随机数。 :p现在我们已经解决了这个问题,最快的方法是使用包含已生成的所有ID的Hashtable或HashMap。每当生成新ID时,请根据哈希表对其进行检查,如果ID已经出现则重新生成。如果学生人数远远少于身份证的范围,这通常会很有效。如果不是,则由于需要重新生成ID的概率增加,您将陷入更深的麻烦,P(生成新ID)= number_of_id_already_generated / number_of_all_possible_ids。在这种情况下,请检查第一段(您是否需要ID是随机的?)。

Hope this helps.

希望这可以帮助。

#7


1  

Many possibilities...

很多可能......

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

你知道如何随机生成一个整数吗?你可以从中生成一个char ...(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 :)

这取决于你需要什么,随机性的水平,所涉及的安全性......但是对于一个学校项目,我想让UUID子串适合:)