【问题标题】:NullPointerException in add() Methodadd() 方法中的 NullPointerException
【发布时间】:2013-03-10 00:12:42
【问题描述】:

我的问题是我为我的ArrayList 创建了一个add() 方法。

我收到了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);
    }
}

【问题讨论】:

  • 粘贴异常的堆栈跟踪。告诉我们它指的是哪条线。并且不要使用 == 来比较字符串,而是使用 equals()
  • if (dict.get(i).getWord() == word) { 应该使用.equals(word) 而不是==

标签: java arraylist nullpointerexception add


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多