123 123 - 29 days ago 7
Java Question

incompatible types: int[] cannot be converted to java.util.List<java.lang.Integer>

I have a function that generates random arrays:

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;
}


I'm getting the following error:


incompatible types: int[] cannot be converted to java.util.List


I'm not sure what the issue is here. This is an incredibly simple bit of code that I can't seem to get to work.

Answer

You're returning List<Integer>, but you're creating an int[]. They're completely different things! try this instead:

  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;
  }

Or if you definitely want to use an array, change the method's declaration:

private static int[] randomIntegerArray(int n)

And be aware that Math.random() returns a value between 0 and 1, if you convert it to an int it'll always be 0.

Comments