I'm trying to remove the empty element from the array by copying the existing element to a new array. However, initialization of the new array is causing my return value to be null even when I initialize it within the for
loop.
public String[] wordsWithout(String[] words, String target) {
for(int i = 0; i < words.length; i = i +1){
String store[] = new String[words.length];
if (words[i] == target){
words[i] ="";
}
else if(words[i] != target){
words[i] = store[i];
}
}
return words;
}
I'm actually not sure what you want to achieve but if you want to remove an empty String out of your array you can do it with streams and filters in java 8 like this:
String[] objects = Arrays.stream(new String[]{"This","", "will", "", "", "work"}).filter(x -> !x.isEmpty()).toArray(String[]::new);
Array are immutable so the size stays the same you need to create a new Array So if you create a new Array base on the Size of the Old array you will still have null elements
If you want to use arrays only you need to count the non null elements in the array to get the size of the new Array. It just easier to use a List/ArrayList
public String[] wordsWithout(String[] words, String target) {
List<String> tempList=new ArrayList<String>();
for(int i = 0; i < words.length; i = i +1){
if (words[i]!=null||words[i].trim().length()>0){
tempList.add(words[i]);
}
}
return (String[]) tempList.toArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With