| Author |
How to extend the size allocated to an integer array after adding some elements to it.
|
Veerabhadraiah As
Greenhorn
Joined: Dec 05, 2011
Posts: 3
|
|
Hello,
I want to extend the memory allocated to my integer array, but all my array elements should be unaltered?
lets say
I have int[] a=[10,20,30];
now i want to extend a's size to 10 but the data in a should be retained.
Hope you understood my problem
thanks in advance, waiting for your valuable replies..:)
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 2686
|
|
|
Arrays are a fixed size - you can't alter it. You will have to create a new array of the required size and copy the contents of the first array into it. Alternatively, use a List of some sort e.g. ArrayList.
|
Joanne
|
 |
Veerabhadraiah As
Greenhorn
Joined: Dec 05, 2011
Posts: 3
|
|
Joanne Neal wrote:Arrays are a fixed size - you can't alter it. You will have to create a new array of the required size and copy the contents of the first array into it. Alternatively, use a List of some sort e.g. ArrayList.
But Copying the contents of old array to new array is ok for small data, what if i have a large amount of data?
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 2686
|
|
Veerabhadraiah As wrote:what if i have a large amount of data?
Then you need to make sure the code that copies the data is efficient.
What I would do is, any time I needed the array to be bigger, I would create a new array that is bigger than the old array by a certain amount. MaybeI would then use the Arrays.copyOf method to create the new array*. Obviously this would create an array bigger than you currently need, so you would need to maintain a pointer to show where the current 'end' of the array is.
* If you are wondering why I suggested doing it like this, open the src.zip file in your JDK installation directory and have a look at the source for ArrayList, which itself is just a wrapper around an array.
|
 |
 |
|
|
subject: How to extend the size allocated to an integer array after adding some elements to it.
|
|
|