7

Possible Duplicate:
How to convert List<Integer> to int[] in Java?

I have an ArrayList and when I try to convert it into an Array of Integer because I need to do operations which concerns integer, I get this error :

incompatible types
required: int[]
found: java.lang.Object[]

Here's my code :

List<Integer> ids_rdv = new ArrayList<Integer>();

// I execute an SQL statement, then :
while (resultat.next()) {
    ids_rdv.add(resultat.getInt("id_rdv"));
}
int[] element_rdv_id = ids_rdv.toArray(); //Problem

Do you have any idea about that?

Community
  • 1
  • 1

2 Answers2

7

Assuming your original objects were instances of the Integer class:

Integer[] element_rdv_id = ids_rdv.toArray(new Integer[0]);
user278064
  • 9,982
  • 1
  • 33
  • 46
  • Thank you !! It works now !! but I still don't understand what did you do ? –  Jun 23 '12 at 18:02
  • 1
    Simply `Integer` isn't the same data type as `int`. Also if you later need any value from this `Integer[]` array you may need to use `element_rdv_id[i].intValue()` instead of `element_rdv_id[i]` as you would expect. – Havelock Jun 23 '12 at 18:04
  • thank you @Havelock :) what about `new Integer[0]` ? –  Jun 23 '12 at 18:08
  • Have a look [here](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28T[]%29) – Havelock Jun 23 '12 at 18:13
0
incompatible types required: int[] found: java.lang.Object[]

when you do ids_rdv.toArray(), it returns an array of Objects, that can't be assigned to array of primitive integer types.

You need to get an array of Integer objects in hand, so write it this way

Integer[] element_rdv_id = ids_rdv.toArray(new Integer[]);
Havelock
  • 6,913
  • 4
  • 34
  • 42
Ahmad
  • 2,110
  • 5
  • 26
  • 36