Java Question

Sizing problems if instead of ArrayList to manage data, use arrays

What if instead of an ArrayList to manage data, I had to use arrays?

How would I have to manage the growth of this, considering the number of elements can exceed the initial size of the array?

Answer Source

You will need to have some sort of heuristics to resize the array. E.g. One of the ideas is to allocate a new array with double the size of the existing array when a new element cannot be added because the array is full. Before you discard the old array, you will need to copy the data from the old array to the new array. Look at Arrays.copyOf to achieve both allocating new array and copying data over.

Yet another alternative is to use a linked list of arrays. Grow the linked list by one every time the existing array is full. This is generally more efficient at runtime because you can resize the array without incurring copying penalty. Of course, it makes the code a tad bit complicated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download