如何有效地将 Set 转换为数组?

Fis*_*hyK 0 java arrays arraylist set

因此,我尝试生成一个充满唯一随机整数的数组,我发现使用数组列表执行此操作将是最有效的方法。

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));
 
        }
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用,randArr = test.toArray()但我不太确定括号里应该放什么,也不确定这是否真的可行。是否还有其他转换方法,因为我也不能简单地通过test.get(i)for 循环将 test 的整数分配给 randArr 。

WJS*_*WJS 6

不要使用一套。Stream随机数,使用 删除重复项distinct,并限制使用limit

public static int [] randArr(int n, int max){
    Random rn = new Random();
    return rn.ints(0,max).distinct().limit(n).toArray(); 
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 确保这一点n is <= max,否则您可能会等待一段时间。
  • max must be >= 1(方法要求Random.ints

您可能需要放入一些代码来强制执行这些操作invariants,并在不符合要求时抛出适当的异常。类似以下内容(或任何对您有意义的内容)。

if (n > max || max <= 0) {
   throw new IllegalArgumentException(
                "n(%d) <= max(%d) or max > 0 not in compliance"
                .formatted(n,max));
}
Run Code Online (Sandbox Code Playgroud)