Java 如何清除android中的int []数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27700614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:53:16  来源:igfitidea点击:

How to clear int[] array in android?

javaarraysintegersum

提问by Reshmin

I have an example that calculates total expense and income. There are some values in integer array that converted from a string array. Once I am running the code the sum is 6000 and running again the same code the sum gets multiplied to 12000. How can I override this problem. Please check my code given below..

我有一个计算总费用和收入的例子。整数数组中有一些值是从字符串数组转换而来的。运行代码后,总和为 6000,再次运行相同的代码,总和将乘以 12000。如何解决此问题。请检查我下面给出的代码..

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

采纳答案by Himanshu Agarwal

You can simply assign nullto the reference. (This will work for any type of array, not just ints)

您可以简单地分配null给参考。(这适用于任何类型的数组,而不仅仅是ints

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

This will 'clear out' the array. You can also assign a new array to that reference if you like:

这将“清除”阵列。如果您愿意,您还可以为该引用分配一个新数组:

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

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

如果您担心内存泄漏,请不要担心。垃圾收集器将清除数组留下的任何引用。

Another example:

另一个例子:

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

This will create a new float[]initialized to the default value for float.

这将创建一个新的float[]初始化为 float 的默认值。

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;

回答by Amit Kumar

public static int incSum=0; 

your variable is staticso when you run again then previous value store in incSumvariable .

static当您再次运行时,您的变量是如此,然后将先前的值存储在incSum变量中。

Remove staticfrom incSum

删除staticincSum