Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove null from an array in java

Tags:

java

arrays

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;
}

Thanks in advance!

like image 645
panther Avatar asked Aug 29 '11 12:08

panther


1 Answers

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

public String[] removeNull(String[] a) {
   ArrayList<String> removedNull = new ArrayList<String>();
   for (String str : a)
      if (str != null)
         removedNull.add(str);
   return removedNull.toArray(new String[0]);
}
like image 140
Garrett Hall Avatar answered Sep 17 '22 10:09

Garrett Hall