• Post Reply Bookmark Topic Watch Topic
  • New Topic

append a value to an array ?  RSS feed

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the easiest and most efficient way to append a value to an array ?

thanks.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah you can't because array is fixed size. A collection is what you need like a list or set. You can make your array to list using Arrays.asList(array) then add items to the list and if need make it back to an array using List.toArray(array_type) or just List.toArray() to get Object[] array.

Another way is to use Arrays.copyOf(original_array, new_length) but then it depends of how often you are modifying the array.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you need to dynamically change the size, you don't want to use an array. Most folks would use an ArrayList (which uses arrays behind the scenes).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!