javaarraysextending

Create an extendable array in Java


I want to create an extendable array.

Whenever you try and add an element into the array and it's full:

Would anyone be able to give me some pointers on how to do this?

EDIT:
Note: I can't use an ArrayList for this.


Solution

  • If you can't use ArrayList, then you'll have to write your own class that basically does the same thing as ArrayList.

    Your class will need to hold a reference to an array, as well as an integer that says how many values have been put into it (since it may be less than the current size of the array).

    When an element is added to the array, check that integer against the array's current size. If it's less than the array's size, it means there's room for another element, so just put the new value into the array using the integer as the index, then add one to the integer. If the integer is equal to or greater than the array's size, it means you need a bigger array, and you'll have to write the code to create a new array and copy all the values to it.

    When you create a bigger array, you'll probably want to make it big enough to hold more than one additional value, so that you don't have to create new arrays (and copy lots of values) every time you add a new element. A common technique is to make the new array size some percentage of the old one, like 150%.