-2

I don't know if it's a mental block for me or what but despite spending hours studying the questions asked already, I just can't pick up the final conclusion. I get lost and confused trying to comprehend so many different answers. :(

Please tell me the best way to do the following. I spent considerable time going through the existent questions but can't get the bottomline.

I'm trying to convert an arraylist into an array and while doing so, another question about object and array typecasting popped up.

    ArrayList<Integer> al = new ArrayList<Integer>();
    al.add(1);
    al.add(2);
    al.add(3);
    Object[] oa = al.toArray();
    int [] a = new int[al.size()];
    a = (int[]) oa;

In the last line, it says I cannot cast from object[] to int[].

So, how do I typecast it then because the toArray method only returns an Object array.

Boyyett
  • 93
  • 1
  • 1
  • 5
  • 1
    Did you read [How to convert List to int in Java?](http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java)? – Pshemo Mar 02 '15 at 20:27

2 Answers2

4

The array oa is an array of Integer objects. And you are trying to cast it to an array of ints.

You have to remember that automatic boxing/unboxing of reference types (Integer) to primitive types (int) doesn't occur when you cast the array to a different type.

RudolphEst
  • 1,240
  • 13
  • 21
  • So, does it mean I have to loop through all the elements and convert each Integer to int using the intValue() method? – Boyyett Mar 02 '15 at 20:31
  • My question would be, why do you need an `int[]` so bad? What's wrong with the `Integer[]` you have already? But the simple answer is yes, there is no _auto-conversion_ between the two... you're doomed to the loop. – RudolphEst Mar 02 '15 at 20:34
  • That doesn't work either. It gives me a class cast exception when I do: `Integer [] a = (Integer []) al.toArray();` – Boyyett Mar 02 '15 at 20:40
  • @boyyett I think you might have misunderstood ... but if you can live with an `Integer[]` this is how you get one: `Integer[] integerArray = al.toArray(new Integer[]{})` – RudolphEst Mar 02 '15 at 22:06
0

You don't cast it; you get the Integers from oa, get each value as an int, which you can put in a.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101