File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes expanding an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "expanding an array" Watch "expanding an array" New topic

expanding an array

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
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 = myarray.expandedArray(1);

or something like that?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Anubhav Anand
Ranch Hand

Joined: May 18, 2007
Posts: 341

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

Joined: Oct 27, 2005
Posts: 20276

If you can't use a List for some reason, you can use the java.util.Arrays.copyOf methods since Java 6.

How To Ask Questions How To Answer Questions
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Thanks for the info.
jQuery in Action, 3rd edition
subject: expanding an array
It's not a secret anymore!