java如何避免使用RandomStringUtils生成重复的数字。apachecommons Jar的随机性
我正在使用ApacheCommonsLang3包类RandomStringUtils
。在生成一些数字之后,RandomStringUtils.randomNumeric
正在无限循环中生成重复的数字。我怎样才能防止这种情况发生
这是我的密码:
quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 1;
while (insertedNum < quantity) {
String random=RandomStringUtils.randomNumeric(length);
numGen[idx - 1] = random;
if (idx == 100) {
insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
idx = 1;
numGen = new String[100];
}
else
idx++;
}
}
# 1 楼答案
一种麻烦的方法是保持重新生成随机字符串,直到发现数组中还没有包含唯一的随机字符串。您所要做的就是检查新生成的随机字符串是否已经在数组中
这里是helper方法isAlreadyInArray(String[]array,String someVal)
请运行这个示例,如果它没有帮助,那么我们当然可以重新迭代这个问题:)
# 2 楼答案
首先你有一个bug numGen[idx-1]=random
当第一次进入循环时,idx为0,因此您将分配给numGen中的-1字段。 第二,它不会永远持续下去,但如果持续很长时间,您可以在生成字符串时采用不同的方法,而不是删除整个批,如果它们存在于当前批中,请逐个重新生成它们
如果此批次中尚未生成编号,请尝试在每一代之后进行检查。您可以使用java map或set标记批处理中所有可见的数字,以便更快地查找
因此,为您的解决方案添加代码,使其符合以下要求: