-2

我的问题是我add()为我的ArrayList.

我得到一个NullPointerException. add()如以下代码所示,如​​何在我的类中实现方法?

这是代码:

public class XY{

    private List<DictEntry> dict = new ArrayList<DictEntry>();

    public void add(String word, int frequency) {
        DictEntry neu = new DictEntry(word, frequency);
        if (word == null || frequency == 0) {
            return;
        }
        if (!dict.isEmpty()) {
            for (int i = 0; i < dict.size(); i++) {
                if (dict.get(i).getWord() == word) {
                    return;
                }
            }
        }
        dict.add(neu);
    }
}
4

2 回答 2

0

没有它被抛出的行号,就很难说。但无论如何,我建议不要采取你的方法。

首先:不要重新实现现有的功能:

public class XY{
private List<DictEntry> dict = new ArrayList<DictEntry>();


    public void add(String word, int frequency) {
       if (word == null || frequency == 0) {
            return;
        }

       DictEntry neu = new DictEntry(word, frequency);
       if (!dict.contains(word)) {
         dict.add(word);
       }
    }
}

更好的是,使用更适合问题的结构。您正在将一个单词映射到一个计数 - 这就是您使用 DictEntry 所做的所有事情,在这里。那么为什么不呢:

public class XY{
private Map<String, Integer> dict = new HashMap<String, Integer>();

    public void add(String word, int frequency) {
       dict.put(word, frequency);
}
于 2013-03-10T00:26:50.417 回答
0

你的数组中有一个null元素。dict.get(i).getWord()就好像null.getWord()

于 2013-03-10T00:20:49.987 回答