本文介绍了Java:随机生成不同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在Java中生成10,000个唯一标识符。标识符应该是数字和字母的混合,每个少于10个字符。有任何想法吗?内置库将是一个额外的加号。
I need to generate 10,000 unique identifiers in Java. The identifiers should be a mixture of numbers and letters and less than 10 characters each. Any ideas? Built in libraries would be an extra plus.
推荐答案
// class variable
final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890";
final java.util.Random rand = new java.util.Random();
// consider using a Map<String,Boolean> to say whether the identifier is being used or not
final Set<String> identifiers = new HashSet<String>();
public String randomIdentifier() {
StringBuilder builder = new StringBuilder();
while(builder.toString().length() == 0) {
int length = rand.nextInt(5)+5;
for(int i = 0; i < length; i++) {
builder.append(lexicon.charAt(rand.nextInt(lexicon.length())));
}
if(identifiers.contains(builder.toString())) {
builder = new StringBuilder();
}
}
return builder.toString();
}
这篇关于Java:随机生成不同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!