0 java
我是Java新手。我看到有些人使用这个函数在 Spring 中返回唯一的 id。此函数是否返回唯一值?
public class Utils {
private final Random RANDOM = new SecureRandom();
private final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private String generateRandomString(int length) {
StringBuilder returnValue = new StringBuilder(length);
for (int i = 0; i < length; i++) {
returnValue.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
}
return new String(returnValue);
}
}
Run Code Online (Sandbox Code Playgroud)
不,它不是独一无二的。它是随机的,但两个随机值可以相同。它发生了。更好的解决方案是使用UUID类:
UUID uuid = UUID.randomUUID();
return uuid.toString();
Run Code Online (Sandbox Code Playgroud)
我无法抗拒在这里链接到Dilbert。两个随机数可以相同!