简体   繁体   中英

Increment count if the object exists in arraylist, else Add the object into arraylist

I read words from a text file and then create a new Word object for each word and store the objects into an ArrayList . The text of the word is passed into the object as a parameter. I have overridden the equals(Object) and hashCode() method of the word class to check for the equality of objects based on text of a word instead of object memory location. I am trying to store all unique words in ArrayList as unique objects and increment the occurrence of the word object if the word repeats in the text file.

Scanner file = new Scanner(new File(textfile));
ArrayList<Word> words = new ArrayList<Word>();
while (file.hasNext()) {

    Word w = new Word(fileWord);

    if (words.contains(w)) {
        w.increaseCount();
    } else {
        words.add(w);
    }
}

Word Class is;

public class Word {
    private String text;
    private int count;

    public Word(String wordText) {
        text = wordText;
    }

    public void increaseCount() {
        count += 1;
    }

    @Override
    public boolean equals(Object wordToCompare) {
        if (wordToCompare instanceof Word) {
            Word castedWord = (Word) wordToCompare;
            if (castedWord.text.equals(this.text)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        return text.hashCode();
    }
}

Unique words get added to the ArrayList , but my count does not increment. How to increment the count

The problem is that you create new instance of Word in the loop. When the array contains the newly created Word, you increase the count for it, not the existing instance which already added to the array before. Consider to use Map for the problem, the key is the word and the value is the count.

package example.stackoverflow;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordCount {

    public static void main(String[] args) {
        List<String> sourceList = Arrays.asList("ABC", "XYZ", "HGK", "ABC", "PWT", "HGK", "ABC");

        Map<String, Integer> wordCount = new HashMap();

        for (String word : sourceList) {
            if (wordCount.get(word) != null) {
                wordCount.put(word, wordCount.get(word) +1);
            } else {
                wordCount.put(word, 1);
            }
        }

        System.out.println(wordCount);//output: {ABC=3, XYZ=1, PWT=1, HGK=2}
    }

}

The problem is with this statement in your code;

while (file.hasNext()) {

    Word w = new Word(fileWord);

    if (words.contains(w)) {
        w.increaseCount(); // Here's what goes wrong.
    } else {
        words.add(w);
    }
}

You're invoking the function increaseCount() on newly created object and that would get replaced during the next iteration, and you lost the reference. But the actual object is in the ArrayList and you should increase the value of that object. So, I would say, your code should be changed like this;

Scanner file = new Scanner(new File(textfile));
ArrayList<Word> words = new ArrayList<Word>();
while (file.hasNext()) {

    Word w = new Word(fileWord);

    if (words.contains(w)) {
        words.get(words.indexOf(w)).increaseCount(); // Note the change here.
    } else {
        w.increaseCount(); // This is for the first occurrence as 'count' is 0 initially.
        words.add(w);
    }
}

Check this answer:

    Scanner file = new Scanner(new File(textfile));
    ArrayList<Word> words = new ArrayList<Word>();
    while (file.hasNext()) {

        Word w = new Word(fileWord);

        if (words.contains(w)) {
            w.increaseCount();
            int index = words.indexOf(w);
            Word w1 = words.get(index);
            w1.increaseCount();
            words.set(index, w1);
        } else {
            words.add(w);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM