I have following String Array
tmp = [null, null, null, Mars, Saturn, Mars]
coming after doing the operation -
allSig[d3].split(\" \");
where
If you want the array to contain only the non-null values (i.e. the resulting array would be ["Mars", "Saturn", "Mars"]
), then I would look at this as a two part problem.
First, you must identify what the size of the new array should be. From inspection, it's easy to see that it's 3
, but you will need to need to count them to calculate this programmatically. You can do this by saying:
// Calculate the size for the new array.
int newSize = 0;
for (int i = 0; i < allElements.length; i++) {
if (allElements[i] != null) {
newSize++;
}
}
Secondly, you will need to create a new array with that size. Then you can put all of the non-null elements into your new array, as you have done above.
// Populate the new array.
String[] _localAllElements = new String[newSize];
int newIndex = 0;
for (int i = 0; i < allElements.length; i++) {
if (allElements[i] != null) {
_localAllElements[newIndex] = allElements[i];
newIndex++;
}
}
// Return the new array.
return _localAllElements;
You can just combine these two components as the new content of your results
method. See the full combined code and live sample output here.