Removing unfilled values or null values from array of String in Java

前端 未结 7 1299
醉话见心
醉话见心 2020-12-16 02:22

I have following String Array tmp = [null, null, null, Mars, Saturn, Mars] coming after doing the operation - allSig[d3].split(\" \"); where

7条回答
  •  不思量自难忘°
    2020-12-16 02:51

    You're creating an array with same size as the original one. So it's the same as the original array, as you copy non null values and default values are null.

    Do this :

    public static String[] removeElements(String[] allElements) {
        // 1 : count
        int n = 0;
        for (int i = 0; i < allElements.length; i++)
            if (allElements[i] != null) n++;
    
        // 2 : allocate new array
        String[] _localAllElements = new String[n];
    
        // 3 : copy not null elements
        int j = 0;
        for (int i = 0; i < allElements.length; i++)
            if (allElements[i] != null)
                _localAllElements[j++] = allElements[i];
    
        return _localAllElements;
    }
    

提交回复
热议问题