Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Any good method to use when converting Integer List to int[]?

 
Mingwei Jiang
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thing is like this: I have a method which has int[] as its return value (the method signature cannot be changed), but in the implementation of this method, I found very hard to define the length of this return value until the end. So I used List to contain return values first and thinking I could extract this list to the int[] and return. But I didn't find any existing method for doing so, I mean converting Integer List to int[]. What I did now is write a separate method to interate over Integer list and construct the int[] to return.

Is there any convenient method there for me to use? Because I feel a little embarrassed to write this conversion like code.
 
John Bartlett
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are converience methods on the List itself, but they deal with objects. e.g.

List<Integer> results = new ArrayList<Integer>();
Integer [] values = results.toArray(new Integer[] {});
[ May 14, 2007: Message edited by: John Bartlett ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have an array of Integer objects, obtained as shown by previous poster, then auto-boxing will allow you to treat the elements as if they were primitive ints.

However, if you really need an array of primitive ints, perhaps because you are going to pass it to a function that requires one, then I think you have no option but to write a little loop.
 
Mingwei Jiang
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, I really need those primitive ints, seems I have no choice but write a little loop.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15636
46
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Apache Jakarta Commons Lang utility library contains a method to do that. Example:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic