1

I need to create a method to return an int array by casting from the ArrayList. Here is my code:

public int[] getDestSets()
{
    int[] array = new int[destSet.size()];
    destSet.toArray(array);
    return array;
}

destSet is an integer ArrayList. I got the error "The method toArray(T[]) in the type ArrayList is not applicable for the arguments (int[])". Can anyone give me a hint? Thanks!

user2570387
  • 15
  • 1
  • 4
  • Doesn't work on primitives. – arynaq Jul 21 '13 at 23:14
  • ArrayList can only hold Objects not primitives. So it is actuallay ArrayList and not int. You need a cast to (int[]) – HectorLector Jul 21 '13 at 23:15
  • may I ask why you need to return an array of int? Arrays should be avoided unless you're dealing with code you don't control that requires it, in which case you should hide that code under an interface that deals with collections. – sjr Jul 21 '13 at 23:22
  • ints have better memory footprint then integers. – morpheus05 Jul 21 '13 at 23:23

3 Answers3

1

An int[] array cannot be "boxed" to an Integer[] array. You have to use a for-loop. See Why don't Java Generics support primitive types? for more information.

Community
  • 1
  • 1
morpheus05
  • 4,772
  • 2
  • 32
  • 47
1

While the wrapper class Integer will be auto unboxed to an int primitive, arrays/Lists are not auto unboxed to arrays of int.

You must do it the hard way:

public int[] getDestSets() {
    int[] array = new int[destSet.size()];
    int x = 0;
    for (Integer i : destSet)
       array[x++] = i;
    return array;
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

You can try use the ArrayUtils class from the Apache Commons Lang library. It will need two steps. First convert the ArrayList to the wrapper object array (Integer[]). After that you can use ArrayUtils.toPrimitive() to convert it to an array of int (int[]).