【问题标题】:How to remove zeros from int array?如何从 int 数组中删除零?
【发布时间】:2015-02-22 15:45:57
【问题描述】:

这是我的数组:int[] test= new int[] {1,0,1,0,0,0,0,0,0,0}

现在我需要从这个数组中删除所有的零,所以它会显示如下:输出:{1,1}

我从link-StackOverFlow 尝试了这段代码,但对我不起作用。

    int j = 0;
    for (int i = 0; i < test.length; i++) {
        if (test[i] != 0)
            test[j++] = test[i];
    }
    int[] newArray = new int[j];
    System.arraycopy(test, 0, newArray, 0, j);
    return newArray;

请帮我解决这个问题。

【问题讨论】:

  • 有什么问题?
  • 它不会从中删除 0,只是返回相同。
  • 我刚刚试过你的代码,它工作正常!新数组 = {1,1}
  • 我只是在之前和之后使用 logcat,但在这里得到相同的结果。
  • 这段代码是正确的,所以,请添加这个方法的完整代码以及你如何传递参数给它。

标签: java arrays int


【解决方案1】:

请改用List。然后你可以做list.removeAll(Collections.singleton(0));。数组更难用于这种事情。

例子:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 0, 2, 0, 3, 0, 0, 4));
list.removeAll(Collections.singleton(0));
System.out.println(list);

输出:[1, 2, 3, 4]

【讨论】:

  • 您好,感谢您抽出宝贵时间,这段代码不起作用,它显示 cannot invoke removeAll(seton array type of int[]) :(
  • 不,它不适用于阵列。您需要使用List&lt;Integer&gt; 而不是int[]。这只是我的建议。等待几分钟,有人会使用int[] 发布答案,但我不建议这样做。
  • 是的,但是我需要动态添加整数,所以我使用了 int[],在运行程序时我使用这样的方式将 int 添加到数组中test = new int[] { Count1, Count2, Count3,
【解决方案2】:

如果你坚持使用数组,你可以使用这个:

int n = 0;
for (int i = 0; i < test.length; i++) {
    if (test[i] != 0)
        n++;
}

int[] newArray = new int[n];
int j=0;

for (int i = 0; i < test.length; i++) {
    if (test[i] != 0)
       { 
         newArray[j]=test[i]; 
         j++;
       }
}

return newArray;

或者尝试使用列表:

List<Integer> list_result = new ArrayList<Integer>();
for( int i=0;  i<test.length;  i++ )
{
    if (test[i] != 0)
        list_result.add(test[i]);
}
return list_result;

解析列表:

for( int i=0;  i<list_result.size();  i++ )
{
        system.out.pintln((Integer)list_result.get(i));
}

【讨论】:

    【解决方案3】:

    我不熟悉Java,但如果有Underscore 或Lo-dash 库可以使用;那么您可以使用 .filter 功能;

    这段代码来自 Swift;

    var numbers = [1,0,1,0,0,0,0,0,0,0]
    numbers = numbers.filter({ $0 != 0 })  // returns [1,1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      相关资源
      最近更新 更多