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
source to share
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;
source to share