如何从int数组中删除零?

时间:2014-12-24 14:24:08

标签: java arrays int

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

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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));
}

答案 2 :(得分:0)

我不熟悉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]
相关问题