从数组中删除所有零

Hid*_*dde 14 java arrays optimization

我有一个数组:

[0, 5, 6, 0, 0, 2, 5]
Run Code Online (Sandbox Code Playgroud)

我想从中删除所有零,以便返回(保持相同的顺序):

[5, 6, 2, 5]
Run Code Online (Sandbox Code Playgroud)

有没有比以下更简单的方法删除所有零?

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++;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我无法在Arrays课程中找到任何方法,Google/SO搜索也没有给我任何好的答案.

Mik*_*kis 16

这是一种罕见的情况,在代码中显示它比用简单的英语解释更容易:

int targetIndex = 0;
for( int sourceIndex = 0;  sourceIndex < array.length;  sourceIndex++ )
{
    if( array[sourceIndex] != 0 )
        array[targetIndex++] = array[sourceIndex];
}
int[] newArray = new int[targetIndex];
System.arraycopy( array, 0, newArray, 0, targetIndex );
return newArray;
Run Code Online (Sandbox Code Playgroud)

  • @Robin不,你没有.那个怎么样? (2认同)
  • @Robin我看了一下文档,看来你是对的.自从我上次用Java编写一行代码以来,已经有很长一段时间了,从那以后我一直在使用C#,其中可以有一个原始`int`s的数组列表.我会纠正我的回答,谢谢. (2认同)

Eng*_*uad 12

这个怎么样:

Integer[] numbers = {1, 3, 6, 0, 4, 0, 3};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(numbers));
list.removeAll(Arrays.asList(Integer.valueOf(0)));
numbers = list.toArray(new Integer[list.size()]);
System.out.println(Arrays.toString(numbers));
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

[1, 3, 6, 4, 3]
Run Code Online (Sandbox Code Playgroud)

  • @ManishGiri 很抱歉回复六年前的评论,你可能已经明白了。也许对其他人有用。创建零大小的数组允许 toArray() 方法使用反射查找返回数组的类型。您必须这样做才能在编译时显式确定返回数组的类型。顺便说一句,这种数组创建在最新版本的 JVM 中得到了很好的优化,并且运行速度很快。 (2认同)

小智 5

使用 Java 8,您可以从数组中创建一个流,应用 .filter() 然后将其转换回数组:

int[] array = {0, 5, 6, 0, 0, 2, 5};

int[] filteredArray = Arrays.stream(array).filter(num -> num != 0).toArray();    

// filteredArray = {5, 6, 2, 5};
Run Code Online (Sandbox Code Playgroud)