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]); }
Advertisement
Answer
You need to reset the tracker every loop, not just when you find a new item.
I also rewrote your code to use lists from the start instead of converting arrays
public static void main(String[] args) { List<WordCount> first = Arrays.asList(new WordCount("I", 1), new WordCount("love", 1), new WordCount("you", 1)); List<WordCount> second = Arrays.asList(new WordCount("I", 1), new WordCount("love", 1), new WordCount("me", 1)); List<WordCount> combined = new ArrayList<>(first); for (WordCount count : second) { int tracker = 0; for (WordCount wordCount : first) { if (count.getWord().equals(wordCount.getWord())) { tracker++; } } if (tracker == 0) { WordCount a = new WordCount(count.getWord(), count.getCount()); a.setCount(0); combined.add(a); } } System.out.println(combined); }