0

Is there an easy way of creating an int[] or the equivalent Integer[] from an ArrayList<Integer>?

When I try (Integer[])list.getArray(), I get this stack trace:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

The only other way I can think of is:

int[] array = new int[list.size()];
for (int i = 0; i < array.size; i++){
    array[i] = list.get(i);
    //or I could do list.remove(0), is there any difference?
}
return array;

but that way seems terribly slow.

1 Answer 1

8
yourIntList.toArray(new Integer[yourIntList.size()]);
Sign up to request clarification or add additional context in comments.

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.