I want to compare two object arrays from the WordCount class and add missing elements from the second array to the first one. My method below converts the first to a list. After that, the for loops check for the same words.
The tracker number is incremented if the same string is detected, and if the tracker remains 0 after the for loop, the object is then added to the first list, as it doesn't exist in the first list. The count of this object is then set to 0.
Lastly, the list is converted back to an array. The problem is that this only returns 3 objects.
In theory, the list with a toString-method should look like this:
[("I", 1), ("love", 1), ("you", 1), ("me", 0)]
The WordCount Class:
public class WordCount {
private String word;
private int count;
public WordCount(String word, int count) {
this.word = word;
this.count = count;
if (count < 0)
count = 0;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
Main method (in another class):
public static void main(String arg[]) {
int tracker = 0;
WordCount[] first;
first = new WordCount[3];
first[0] = new WordCount("I", 1);
first[1] = new WordCount("love", 1);
first[2] = new WordCount("you", 1);
ArrayList<WordCount> list = new ArrayList<>(Arrays.asList(first));
WordCount[] second;
second = new WordCount[3];
second[0] = new WordCount("I", 1);
second[1] = new WordCount("love", 1);
second[2] = new WordCount("me", 1);
for (int i = 0; i < second.length; i++) {
for (int j = 0; j < first.length; j++) {
if (second[i].getWord().equals(first[j].getWord())) {
tracker++;
} else
continue;
}
if (tracker == 0) {
WordCount a = new WordCount(second[i].getWord(), second[i].getCount());
a.setCount(0);
list.add(a);
tracker = 0;
}
}
WordCount[] lastList = list.toArray(new WordCount[0]);
}