生成特定范围内的随机数

时间:2016-01-27 18:25:14

标签: java android random secure-random

我正在尝试在我的Android代码中生成0到31之间的n个随机数。 以下是我正在使用的代码:

int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;

while (i != indices_length-1) {
    random_temp = secureRandom.nextInt(max_range);
    if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
        digestCodeIndicesArr[i] = random_temp;
        i++;
    }
}

indices_length是我需要的随机数。它通常是6,7或9.但是当我打印生成的数组时,我通常最终看到重复。有人可以指出我正在犯的错误。我添加了以下代码行来过滤掉随机重复项:

if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))

提前致谢!

2 个答案:

答案 0 :(得分:1)

Arrays.asList(digestCodeIndicesArr)不会生成List<Integer> size() == digestCodeIndicesArr.length 它产生List<int[]> size() == 1,其中第一个(也是唯一的)元素是数组 因此,它永远不会包含random_temp,因此! contains()始终为真。

不断创建列表并执行顺序搜索来检查重复项,这对性能不利。改为使用Set,与数组并行维护,或先使用LinkedHashSet,然后转换为数组。

无论如何,这解释了为什么你的代码无效。 Tunaki提供的重复链接和我在评论中提供的duplicate link解释了如何实际执行您想要做的事情。

答案 1 :(得分:1)

您需要更改:

int[] digestCodeIndicesArr = new int[indices_length];

为:

Integer[] digestCodeIndicesArr = new Integer[indices_length];

因为Arrays.asList(digestCodeIndicesArr)List<int[]>,而不是您的想法(我猜是List<int>List<Integer>)。

相关问题