permaculture playing cards*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "expanding an array" Watch "expanding an array" New topic
Author

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.makeBiggerByOne();
or
myarray = myarray.expandedArray(1);

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

Joined: Aug 16, 2005
Posts: 14114
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
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
Sheriff

Joined: Oct 27, 2005
Posts: 19674
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Thanks for the info.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: expanding an array