Java 在特定范围内生成随机数

Java 在特定范围内生成随机数,java,android,random,secure-random,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 = secur

我试图在我的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++;
    }
}
索引\u length
是我需要的随机数。通常是6、7或9。但是当我打印生成的数组时,通常会看到重复的数组。有人能指出我犯的错误吗。我添加了以下代码行以过滤掉随机重复项:

if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))
提前谢谢

数组.asList(digestCodeIndicateSarr)
不会生成具有
size()==digestCodeIndicateSarr.length的
列表
它生成一个
列表
,其
大小()==1
,其中第一个(也是唯一一个)元素是数组。
因此,它永远不会包含
random_temp
,因此
!contains()
始终为真

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

无论如何,这解释了为什么你的代码不起作用。Tunaki提供的重复链接和我在评论中提供的链接解释了如何实际执行您试图执行的操作。

您需要更改:

int[] digestCodeIndicesArr = new int[indices_length];
致:


因为
Arrays.asList(digestCodeIndicatesar)
List
,而不是你所想的(
List
List
我猜)。

@Tunaki,我们甚至还不知道他想要实现什么,你怎么能说这是一个重复呢?@Gavriel我们知道,因为OP说“看到重复”是一个“错误”@Andreas:我并不是说看到复制品是一个错误。即使我已经检查了我的数组,我也不知道我的数组中是如何填充重复的。很公平,重新打开了。虽然@Tunaki提供的重复链接没有告诉你你做错了什么,但它确实告诉了你如何做对。如中所述,您使用的
数组.asList
是错误的。
Integer[] digestCodeIndicesArr = new Integer[indices_length];