Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to extend the size allocated to an integer array after adding some elements to it.

 
Veerabhadraiah As
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Veerabhadraiah As
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic