Forums Register Login

Array resizing

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
HTH
Art
[This message has been edited by Art Metzer (edited April 04, 2001).]
+Pie Number of slices to send: Send
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!!
Michael
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
OP
I brought this back from the farm where they grow the tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 17318 times.
Similar Threads
Why initial size of String Buffer is 16
LinkedHashMap- When to specify size and Load Factor
Add an object to Array of Objects
stringbuffers
Making a String[] from ResultSet
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 02:14:26.