Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't arrays expandable?

Tags:

java

arrays

size

When we create an array, we cannot change its size; it's fixed. OK, seems nice, we can create a new bigger array and copy the values one by one and that's little slow. What's the technical background of it?

like image 810
Mustafa Avatar asked May 10 '10 18:05

Mustafa


People also ask

Why can't we change the size of an array?

If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

Can an array be expanded?

Extending an array after initialization: As we can't modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared.

Is it possible to resize an array?

An array cannot be resized dynamically in Java. One approach is to use java. util. ArrayList(or java.

Do arrays have a size limit?

The theoretical maximum Java array size is 2,147,483,647 elements. To find the size of a Java array, query an array's length property.


1 Answers

This question didn't mention a language so I'm going to choose 'C' based arrays for my answer.

Arrays are allocated as a single chunk of memory. Growing an array is problematic because the only way to do it properly is to grow it at the end. For a growth of size N there must be at least N free bytes at the end of the array before the next allocated address.

Supporting this type of allocation necessitates that allocations be spread across the virtual address space. This both removes the benefits of having memory allocations closer to each other and serves to increase fragmentation. This flies in the face of most memory managers which try to pack memory together and reduce fragmentation.

Allocating a new array at a place in memory with sufficient space and copying the array there is simply not an option as a general solution. The reason why is that the previous location of the array is visible to consumers through pointers.

int* array = malloc(int*someSize);
int* pointer1 = &(arr[2]);
growArray(&array, 12);  // Can't move because pointer1 knows the address of the array
like image 61
JaredPar Avatar answered Oct 11 '22 02:10

JaredPar