Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

expanding an array

 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I want to make an array bigger than it already is (more elements), I usually just make a new array which is bigger, then copy all the elements in the old array to the new array. Like this:

String[] myarray = new Array[10];
// fill up the array
// oops! I need to add another element!
String[] newarray = new Array[11];
System.arraycopy(myarray, 0, newarray, 0, 10);
myarray = newarray;

Isn't there some simple way to make an array bigger than it already is, like

myarray.makeBiggerByOne();
or
myarray = myarray.expandedArray(1);

or something like that?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15279
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is really no simpler way.

As you know, an array has a fixed size once it's created. If you need to store a list of items with a variable size, then it's better to use a List (for example an ArrayList or a LinkedList) instead of an array.

See the Collections lesson in Sun's Java Tutorials.
 
Anubhav Anand
Ranch Hand
Posts: 341
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Jesper said if you require to change the size Collection classes are better suited. Also, you can get array object from the collection object whenever you require.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you can't use a List for some reason, you can use the java.util.Arrays.copyOf methods since Java 6.
 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the info.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic