I am trying to compare a string to an array of strings and add the string to the array if it is already not in the array.
I tried
String [] array =new String [100];
for (int i=0; i<counter; i++){
if(!str.equals(arry[i])){
array[i]=str;
counter++;
}
}
It doesn’t seem to work.
So basicaly if array = (mike, john, tom, bob);
and the new string is tony, it is supposed to compare tony to the array and add it to the array. But if the next string is mike, not add it to the array as it is already in the list.
An array has a fixed size, so adding an element to an array is not something easy. The behavior that you want is exactly the behavior of a
java.util.Set. Learn how to use the standard collections : they’re much more powerful than arrays. If you want to preserve the order of the elements, then use a LinkedHashSet. See http://download.oracle.com/javase/tutorial/collections/.Now, why does your code fail?
You’re iterating through the array, and as soon as you find one element that is not equal to the string, you replace it with the string. And you also iterate without taking the length of the array in consideration. Here’s the code you might want :