Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dynamic Array (ArrayList)

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I needed a dynamic array so I did an ArrayList. My actual method needs to return a int array. SO in order to do that do I have to declare an in array of the size of my ArrayList and then get each element out convert it to an int and then put it into my int array or is there a way I can do it in one shot w/o a loop?
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anthony -
You can get part way there by calling the toArray( ) method, that'll get you an array of Objects...
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, assuming your ArrayList contains Integer objects, you can get a tiny bit further with

This way you have an Integer[] rather than an Object[]. But still, if what you really wanted was an int[], you need a loop. And as long as you have to do that anyway, you might as well forget the toArray() stuff and build the array you want directly:

It would be nice if there were a one-liner for this, but it's not that big a deal really...
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic