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!

4
  • Doesn't work on primitives. Commented Jul 21, 2013 at 23:14
  • ArrayList can only hold Objects not primitives. So it is actuallay ArrayList<Integer> and not int. You need a cast to (int[]) Commented Jul 21, 2013 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. Commented Jul 21, 2013 at 23:22
  • ints have better memory footprint then integers. Commented Jul 21, 2013 at 23:23

3 Answers 3

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[]).

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.