如何在Java中生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2863852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:50:17  来源:igfitidea点击:

How to generate a random String in Java

javastringrandomchar

提问by chandra wibowo

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,它有studentNamestudentIdstudentAddress等。对于studentId,我必须生成由七个数字字符组成的随机字符串,例如。

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

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

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

回答by Jon Skeet

Generating a random string of characters is easy - just use java.util.Randomand 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.

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

回答by Chris Henry

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 Hashtableor HashMapcontaining 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 现在我们已经解决了这个问题,最快的方法是让一个HashtableHashMap包含已经生成的所有 ID。每当生成新 ID 时,对照哈希表检查它,如果 ID 已经出现,则重新生成。如果学生人数远小于 ID 的范围,这通常会很好地工作。如果没有,随着需要重新生成 ID 的可能性增加,您将陷入更深的麻烦,P(生成新 ID) = number_of_id_already_generated / number_of_all_possible_ids。在这种情况下,请检查第一段(您需要 ID 是随机的吗?)。

Hope this helps.

希望这可以帮助。

回答by David Soroko

This is very nice:

这是非常好的:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html- something like RandomStringUtils.randomNumeric(7).

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html- 类似RandomStringUtils.randomNumeric(7).

There are 10^7 equiprobable (if java.util.Randomis not broken) distinct values so uniqueness may be a concern.

有 10^7 个等概率的(如果java.util.Random没有被破坏)不同的值,所以唯一性可能是一个问题。

回答by Parth

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

您还可以使用 java.util 包中的 UUID 类,它返回 32 位字符串的随机 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

回答by Sebastien Lorber

Many possibilities...

多种可能性...

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

你知道如何随机生成一个整数吗?因此,您可以从中生成一个字符...(例如 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 子字符串会适合:)

回答by Erol Ozcan

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

}

回答by karthik.j

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