Reputation: 65
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;
}
Upvotes: 5
Views: 12161
Reputation: 130
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();
}
Upvotes: 2
Reputation: 317
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].
Upvotes: 1
Reputation: 1254
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);
Upvotes: 8
Reputation: 5336
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))
Upvotes: 0
Reputation: 34920
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.
Upvotes: 0