不兼容的类型:int []无法转换为java.util.List <java.lang.Integer>

123*_*123 -7 java arrays list

我有一个生成随机数组的函数:

  private static List<Integer> randomIntegerArray(int n) {
    int[] array = new int[n];
    for(int i = 0; i <  array.length; i++) {
      array[i] = (int)Math.random();
    }
    return array;
  }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

不兼容的类型:int []无法转换为java.util.List

我不确定这里的问题是什么.这是一个非常简单的代码,我似乎无法开始工作.

Ósc*_*pez 7

你回来了List<Integer>,但是你正在创造一个int[].他们是完全不同的东西!试试这个:

  private static List<Integer> randomIntegerArray(int n) {
    List<Integer> list = new ArrayList<>();
    for(int i = 0; i < n; i++) {
      list.add((int) Math.random()); // always returns 0
    }
    return list;
  }
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实想要使用数组,请更改方法的声明:

private static int[] randomIntegerArray(int n)
Run Code Online (Sandbox Code Playgroud)

而且要知道,Math.random()返回之间的值01,如果你把它转换成int它会永远0.