Saturday, April 9, 2011

remove negative numbers from int array java

Well you may be wondering how on earth can you remove negative numbers from a int array. You cannot physically remove negative numbers that would result in a reduction in the size of the array because arrays are immutable. One thing that you can do is that if the array is used in a situation where certain numbers are ignored then you can assign that number in place of negatives. Like this

int myArray[] = {6,-5,44,33,2,-66,7};

int x = 0;  // here x is a number that has no effect on the array's use

for(int i =0; i < array.length; i++){

if(myArray[i] > 0 ) myArray[i]=x;

}

}


The other thing that you can do is copy only the positive numbers to a new array. Wow thats fun right. But the problem is how can you determine the size of the new array ? Well obviously you can loop throught the first array once to find out the number of positive integers. And next create a new array whose length is equal to that positive integer count.

int myArray[] = {66,88,4,-4,66,-33};

int count = 0 ;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) count++;

}


next step is to create a new array whose size = count

int newArray[] = new int[count];


and the last step is to loop throught the myArray once again and copy only the positives

int position = 0;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) newArray[position] = myArray[i];
position++;
}


Okay so you end up with two arrays. any newArray contains the required result. However you can make myArray to refer to newArray and make the old reference to myArray garbage collected.

myArray = newArray;


Okay so we have removed negative integers by using two loops.

The method below makes use of arrayLists. It first scans through the array and inserts the positive integers into a arraylist. Next a new array is created whose size matches the arraylist. And the array list contents are then copied to the new array. And finally this method returns the newly created int array reference.

static int[] remove_negative(int array[]){

ArrayList<Integer> al = new ArrayList<Integer>();

for(int i =0; i < array.length; i++){

if(array[i] >= 0){
al.add(array[i]);
}

}

int new_array[] = new int[al.size()];

for(int i =0 ; i < al.size() ; i++){
new_array[i] = al.get(i);
}

return new_array;
}

3 comments:

  1. "I very much enjoyed this article.Nice article thanks for given this information. i hope it useful to many pepole.php jobs in hyderabad.
    "

    ReplyDelete