How do I clear an int [] array in android?

I have an example that calculates total expenses and income. The integer array contains values ​​that are converted from the string array. When I run the code, the sum is 6000 and runs the same code again, the sum is multiplied by 12000. How can I override this problem. Please check my code below.

public static int incSum=0;

int[] numbersinc = new int[theAmount.length];

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

        numbersinc[i]=Integer.parseInt(theAmount[i]);

        incSum=incSum+numbersinc[i];
    }

    Log.e("SUM INC","Sum Inc= "+incSum);    <<<<<- This sum is multiplying

      

+3


source to share


2 answers


You can simply assign to the null

link. (This will work for any array type, not just ints

)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

      

This will "clear" the array. You can also assign a new array to this link if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

      

If you're concerned about memory leaks, don't. The garbage collector will clean up any references left behind by the array.



Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

      

This will create a new one float[]

, initialized with the default float value.

So, in your code, try this:

public int incSum=0;

int[] numbersinc = new int[theAmount.length];
incSum = 0; //add this line
    for(int i=0;i<theAmount.length;i++)
    {

        numbersinc[i]=Integer.parseInt(theAmount[i]);

        incSum=incSum+numbersinc[i];
    }

    Log.e("SUM INC","Sum Inc= "+incSum);    <<<<<- This sum is multiplying
  numbersinc = null;

      

+8


source


public static int incSum=0; 

      

your variable static

, so on restart then the previous value is stored in the variable incSum

.



Remove static

fromincSum

+1


source







All Articles