• Post Reply Bookmark Topic Watch Topic
  • New Topic

Convert ArrayList of Integers to int[]  RSS feed

 
Jim Petersson
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Is there any "nice" way to convert an ArrayList of Integers to an array of ints? First I thought it may be possible with the toArray method, (but I guess not since ints aren't Objects.)
The only "solution" I've found is to loop over the ArrayList and add the Integers to the array manually, but I was hoping for a more elegant way to do it.

Thanks
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There isn't. int[] and Integer[] are not compatible, and all you can get from Collection / List etc is Object[] or Integer[].

For a second I thought that you could try using the toArray method that takes an array as parameter, but I realized that although the assignment inside the method would probably work, the method signature itself won't allow it.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With Java 5's generics, autoboxing, Integer and int are closer to equal than ever.

list.toArray() will get you an array of Integer objects,

with the above, and the enhanced for loop the following will do the job...

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!