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
There are few things Which I am putting as points below. Hope you will get help from this.
String store[] = new String[words.length] instantiates an array of
Strings but It does not instantiate any of the elements with any non
null value. Default value is null so this is an array of null
Strings.(words[i] != target) should be replaced with
(!words[i].equals(target))
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();
}
To check the equality use .equals() method i-e string1.equals(string2) and to check non-equality you can use the same method but with not(!) operator i-e. !string1.equals(string2). You should declare the store array outside the loop because in each iteration it makes a new object onamed store. In the else condition do this store[i] = words[i].
You shouldn't compare strings using == operator. This is incorrect, because strings are objects. Use .equals() method instead, this should fix your problem.
Rest part of your code is quite confusing, it's hard to understand what you are trying to achieve: you create new string array store each time in loop iterations, and then assign its null (by default) values to words[i]. You should elaborate your code and algorithm.
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);