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