The moose likes Beginning Java and the fly likes Array resizing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array resizing" Watch "Array resizing" New topic

Array resizing

Ben Hodgson

Joined: Nov 02, 2000
Posts: 12
How do you dynamically resize an array? I'd like to declare it with an initial size, but add to its size if I go out of bounds.
So I'd start with:
String sStuff[] = new String[100];
to get the initial size - is there a way to up the size by, say, 10 elements a time if I need to?
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
The short answer here, Ben, is "no". You cannot dynamically resize an array.
But why not look into <pre>java.util.Vector</pre> instead? Read all about it.
[This message has been edited by Art Metzer (edited April 04, 2001).]
Michael Waites

Joined: Mar 30, 2001
Posts: 8
You can write a method that will expand the array (by cheating) but it is clumsy and somewhat backwards when compared to Vector. But here ya go anywho:

Good luck!!
Ben Hodgson

Joined: Nov 02, 2000
Posts: 12
Excellent - I liked both of those. I'm happy using Vectors, so I'll probably stick with them. Good to find out about the array thing (and the work around), so thanks for the answers, very much appreciated.
octavyn pittman
Ranch Hand

Joined: Mar 06, 2001
Posts: 134
Remember, however, that arrays typically perform better than Vectors, if that is a consideration later on.
And, as Peter Haggar points out in his book Practical Java, there is a System class in the java.lang package with a method called
arraycopy(Obj src, int src_pos, Obj dest, int dest_pos, int length);
It takes a sorce array and a destination array, and using starting positions and a length, to quickly copy an array (nearly twice as fast as a for loop).
The code would look like this:

Apparently this is faster because the method is implemented as a native method, which can more directly and efficiently transfer the contents in memory from source to destination.
However, the arraycopy method has a number of gotchas to watch out for if you look in the API when you go beyond simple copying like above.
I agree. Here's the link:
subject: Array resizing
It's not a secret anymore!