Skip to content

Instantly share code, notes, and snippets.

@RavuAlHemio
Created September 26, 2011 02:53
Show Gist options
  • Save RavuAlHemio/1241518 to your computer and use it in GitHub Desktop.
Save RavuAlHemio/1241518 to your computer and use it in GitHub Desktop.
Dynamically growing array in Java
public class GrowingArray
{
Object[] array;
int count;
int capacity;
public void appending(Object obj)
{
// grow array if needed
if (count == capacity)
{
int i, newLen = capacity + 3; /* 3 is an arbitrary increment here */
Object[] newArray = new Object[newLen];
for (i = 0; i < count; ++i) // copy items
{
newArray[i] = array[i];
}
array = newArray;
}
array[count] = obj;
++count;
}
}
@irfangerard44
Copy link

Nice

@cjburkey01
Copy link

Generally, it is recommended to use System.arraycopy as it's faster than iterating over individual elements.

@DifferentialityDevelopment
Copy link

So I tried my hand at writing an extension to this that handles growing, shrinking, adding and removing. Busy learning Java so excuse me if the code sucks, what do you think?
`
public class DynamicArray {

public Object[] arr = {};

public void push(Object obj){
    growArr(arr.length);
    arr[arr.length-1] = obj;
}

public void set(Object obj, int index){
    if(arr.length < index){
        growArr(index);
    }
    arr[index] = obj;
}

public void remove(int index){
    arr[index] = null;
    shrinkArr();
}

public void shrinkArr(){
    int totalNotNull = 0;
    for(int i = 0; i < arr.length; i++) {
        if(arr[i] != null)
            totalNotNull++;
    }
    Object[] tempArr = new Object[totalNotNull];
    int currentPos = 0;
    for(int i = 0; i < arr.length; i++) {
        if(arr[i] != null){
            tempArr[currentPos] = arr[i];
            currentPos++;
        }
    }
    arr = new Object[totalNotNull];
    System.arraycopy(tempArr,0,arr,0,tempArr.length);
    tempArr = null;
}


public void growArr(int newSize){
    System.out.println("Current: " + arr.length + ", New: " + newSize);
    if(arr.length > 0){
        Object[] tempArr = new Object[(newSize)];
        System.arraycopy(arr,0,tempArr,0,arr.length);
        arr = new Object[(newSize+1)];
        System.arraycopy(tempArr,0,arr,0,tempArr.length);
        tempArr = null;
    }
    else{
        arr = new Object[1];
    }
}

public void readOutArray(){
    for(int i = 0; i < arr.length; i++){
        System.out.println("Arr "+i+":"+arr[i]);
    }
}

}

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment