我有一个数组:
[0, 5, 6, 0, 0, 2, 5]
我想将其中所有的零删除,以便返回以下结果(保持相同顺序):[5, 6, 2, 5]
有没有比下面更简单的方法来删除所有零?
int[] array = {0, 5, 6, 0, 0, 2, 5};
int len = 0;
for (int i=0; i<array.length; i++){
if (array[i] != 0)
len++;
}
int [] newArray = new int[len];
for (int i=0, j=0; i<array.length; i++){
if (array[i] != 0) {
newArray[j] = array[i];
j++;
}
}
我找不到Arrays类中的任何方法,Google/SO搜索也没有给我好的答案。