Tuesday, February 05, 2008

Remove from Array : Java Quickie

lets say you have a problem . You have an array of N numbers . You want to remove the i th number . Then you need a new array not containing the j th number . You are using java . How can you do it ??

Here 's a quickie:

int[] result = null;

result = new int[n-1];
if(i > 0 ) System.arraycopy(array,0,result,0,i);
if(i+1 < n ) System.arraycopy(array,i+1,result,i,n-1-i);

}

This is quick way of removing the element you need and getting a new array devoid of the removed number .

1 comment:

Shyam said...

why do u need a for loop?

int[] remove(int[] array, int j) {
int[] result = new int[array.length-1];
System.arraycopy(array, 0, result, 0, j);
System.arraycopy(array, j + 1, result, j, array.length-j-1);
return result;
}