简体   繁体   English

如果对象存在于数组列表中,则增加计数,否则将对象添加到数组列表中

[英]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 .我从文本文件中读取单词,然后为每个单词创建一个新的Word对象并将这些对象存储到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.我已经重写了单词类的equals(Object)hashCode()方法,以根据单词的文本而不是对象内存位置来检查对象的相等性。 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.我试图将ArrayList所有唯一单词存储为唯一对象,如果单词在文本文件中重复,则增加单词对象的出现次数。

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.独特的词被添加到ArrayList ,但我的计数没有增加。 How to increment the count如何增加计数

The problem is that you create new instance of Word in the loop.问题是您在循环中创建了 Word 的新实例。 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.当数组包含新创建的 Word 时,增加它的计数,而不是之前已经添加到数组的现有实例。 Consider to use Map for the problem, the key is the word and the value is the count.考虑使用Map来解决这个问题,key是word,value是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.您在新创建的对象上调用函数increaseCount()并且在下一次迭代期间将被替换,并且您丢失了引用。 But the actual object is in the ArrayList and you should increase the value of that object.但实际对象在ArrayList ,您应该增加该对象的值。 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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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