Remove Null Value from String array in java

前端 未结 8 619
囚心锁ツ
囚心锁ツ 2020-11-29 08:16

How to remove null value from String array in java?

String[] firstArray = {\"test1\",\"\",\"test2\",\"test4\",\"\"};

I need the \"firstArra

相关标签:
8条回答
  • 2020-11-29 08:53

    Those are zero-length strings, not null. But if you want to remove them:

    firstArray[0] refers to the first element
    firstArray[1] refers to the second element
    

    You can move the second into the first thusly:

    firstArray[0]  = firstArray[1]
    

    If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

    0 讨论(0)
  • 2020-11-29 08:55

    A gc-friendly piece of code:

    public static<X> X[] arrayOfNotNull(X[] array) {
        for (int p=0, N=array.length; p<N; ++p) {
            if (array[p] == null) {
                int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
                X[] res = Arrays.copyOf(array, m);
                for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
                return res;
            }
        }
        return array;
    }
    

    It returns the original array if it contains no nulls. It does not modify the original array.

    0 讨论(0)
提交回复
热议问题