如何从Java中的数组中删除空 [英] How to remove null from an array in java

查看:173
本文介绍了如何从Java中的数组中删除空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了从一个数组,我需要在程序中删除空值的方法。
该方法,但似乎并没有工作,空值不会消失。这是我的code为止。

I've written a method to remove null-values from an array i need in a program. The method, however, doesn't seem to work, the null values won't go away. This is my code so far.

public void removeNull(String[] a)
{
       for(int i=0; i<a.length; i++)
    {
        if(a[i] == null)
        {
            fillArray(a, i);
        }
    }
}

public void fillArray(String[] a, int i)
{
    String[] a2 = new String[a.length-1];

    for(int j=0; j<a2.length; j++)
    {
            if(j<i)
            {
                a2[j]=a[j];
            }
        else if(j>i)
        {
            a2[j]=a[j+1];
        }
    }

    a=a2;
}

在此先感谢!

推荐答案

我会主张这样做的简单的方法,除非性能真的有问题:

I would advocate doing it the simple way unless performance is really a problem:

public String[] removeNull(String[] a) {
   Arraylist<String> removed = new Arraylist<String>();
   for (String str : a)
      if (str != null)
         removed.add(str);
   return removed.toArray(new String[0]);
}

这篇关于如何从Java中的数组中删除空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆