-3
    Temp = ReadLeaderboard();
    int[] TrueLeaderboards = Temp.toArray(new int[Temp.size()]);

The ArrayList Temp reads the data correctly, but when i try cast it and store into a normal Array of integers it won't allow it?

3 Answers3

4

You could use streams to accomplish this.

List<Integer> integers = magicSupplier();  // however it is that you get the list
int[] ints = integers.stream().mapToInt(Integer::intValue).toArray();

Otherwise, you need to unbox the Integer to int, as the object Integer is not a primitive int. The fact that you need to unbox this is why your code doesn't work: you are basically providing an int[] to be populated by Integer.

Also, Java naming conventions state that you should name variables (unless they are constants) with lowercase names, i.e. your Temp variable should be called temp. Only objects should be capitalised like Temp.

ifly6
  • 5,003
  • 2
  • 24
  • 47
2

It won't allow you to send an int[] into the toArray method, because that method accepts an array of a type parameter, which must be a reference type, not a primitive type such as int.

public <T> T[] toArray(T[] a)

You can use Arrays.setAll to copy the elements into an array you've created. That method takes an IntUnaryOperator that supplies an index and expects the value.

int[] arr = new int[temp.size()];
Arrays.setAll(arr, index -> temp.get(index));

There are overloads of Arrays.setAll for setting long[], double[], and T[] arrays, as well as corresponding parallelSetAll methods that are parallel versions of each method.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

You cannot use a primitive array as a generic parameter. See Why don't Java Generics support primitive types? and use a primitive wrapper instead:

Integer[] array = list.toArray(new Integer[list.size()]);
Cardinal System
  • 2,749
  • 3
  • 21
  • 42