gpt4 book ai didi

java - 如何从 int 数组中删除零?

转载 作者:行者123 更新时间:2023-11-30 06:16:15 25 4
gpt4 key购买 nike

这是我的数组: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;

请帮我解决这个问题。

最佳答案

改用 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]

关于java - 如何从 int 数组中删除零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27638343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com