如何有效地将设置转换为阵列?
因此,我试图生成一个装有独特的随机整数的数组,我发现使用阵列列表执行此操作将是最有效的方法。
public static int [] randArr(int n, int max){
randArr = new int[n];
Random rn = new Random();
Set<Integer> test = new HashSet<Integer>();
while(test.size() < n){
test.add(rn.nextInt(0, max));
}
}
现在,我尝试使用randarr = test.toArray()
,但我不太确定,放入括号中的内容或是否真的可以使用。是否还有其他方法可以转换,因为我不能简单地通过test.get(i)
使用for-loop分配randarr。
So I am trying to generate an array that is filled with unique randomized integers and I found out that doing this with an arraylist would be the most efficient way to do so.
public static int [] randArr(int n, int max){
randArr = new int[n];
Random rn = new Random();
Set<Integer> test = new HashSet<Integer>();
while(test.size() < n){
test.add(rn.nextInt(0, max));
}
}
Now I tried working with randArr = test.toArray()
but I am not quite sure, what to put in the parentheses nor if this really can work. Is there any other method for converting, since I cannot simply assign randArr with the integers of test through test.get(i)
with a for-loop either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用集合。
流
随机数,使用不同的
删除DUP,并使用limit
注释:
> n是&lt; = max
,否则您可能会等一会儿。Max必须为&gt; = 1
(Random.ints.ints
方法要求)您可能需要放入一些代码来执行这些
不变性
并投掷如果不符合规定,则适当的例外。类似以下内容(或对您有意义的事)。Don't use a set.
Stream
the random numbers, remove dups usingdistinct
, and limit usinglimit
Notes:
n is <= max
, otherwise you could be waiting a while.max must be >= 1
(required byRandom.ints
method)You may want to put in some code to enforce those
invariants
and throw an appropriate exception if not in compliance. Something like the following (or whatever makes sense to you).