| 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
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
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: 19216
|
|
|
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
How To Ask Questions How To Answer Questions
|
 |
Kevin Tysen
Ranch Hand
Joined: Oct 12, 2005
Posts: 255
|
|
|
Thanks for the info.
|
 |
 |
|
|
subject: expanding an array
|
|
|