【问题标题】:NullPointerException with an ArrayList inside of a HashMap [closed]NullPointerException 与 HashMap 内的 ArrayList [关闭]
【发布时间】:2014-08-06 12:22:39
【问题描述】:

我正在尝试使用 hashmap 内的 arraylist 来创建和迭代提供给 processLine 方法的不同字符的计数器。我想我已经声明了所有变量,catch 语句应该处理哈希图中没有条目的情况,但我仍然在 curCounts.set(i, 1); 上收到 NullPointerException。 行在第二个 catch 语句中。我可能犯了一些愚蠢的错误,但我无法弄清楚它是什么。

HashMap<Character, ArrayList<Integer>> charCounts;

public DigitCount() { charCounts = new HashMap<>(); }


public void processLine (String curLine) {

    int length = curLine.length();
    char curChar;
    ArrayList<Integer> curCounts;
    Integer curCount;

    for(int i = 0; i < length; i++){
        curChar = curLine.charAt(i);
        try {
            curCounts = charCounts.get(i);
        } catch (NullPointerException ex) {
            curCounts = new ArrayList<>();
        }

        try {
            curCount = curCounts.get(i);
            curCount++;
            curCounts.set(i, curCount);
        } catch (NullPointerException ex) {
            curCounts.set(i, 1);
        }

        charCounts.put(curChar, curCounts);
    }

    linesProcessed++;
    System.out.println("---------------------------" + linesProcessed);
}

编辑:是的,我确实调用了 DigitCount。

public static void main(String args[]) throws Exception
{
    //creates an instance of the digitCount object and starts the run method
    DigitCount counter = new DigitCount();
    counter.run(args[0]);
}

【问题讨论】:

  • curCounts 未初始化。您在 for 循环之前的代码行应该是 ArrayList curCounts = new ArrayList();
  • 您可以删除 try/catch 块。另外,你可以'put'和int,我不认为它必须是整数。
  • curCounts = charCounts.get(i); if (curCounts==null) {curCounts= new ArrayList&lt;&gt;();charCounts.put(i,curCounts)} ...
  • 在调用processLine 之前,你是在调用你的方法DigitCount 吗?
  • @user3723352 不是initialize,而是declare 变量curCounts 作为ArrayList o 类型Integer。初始化意味着,创建一个该类型的新对象,即ArrayList&lt;Integer&gt; curCounts = new ArrayList &lt;Integer&gt;();

标签: java arraylist nullpointerexception hashmap


【解决方案1】:

如果 charConts 不包含 i(如 charCounts.get(i)),那么它不会抛出 NullPointerException,它会返回 null。因此,您应该使用 if 而不是 trycatch,如下所示:

curCounts = charCounts.get(i);
if(curCounts==null)
    curCounts = new ArrayList<>();

编辑:或者,如果您使用的是 java 8,您可以这样做

curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());

如果不包含ArrayList,它将自动默认创建一个新的@

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 2013-02-12
    • 2013-05-08
    • 1970-01-01
    • 2013-10-26
    • 2010-12-04
    • 2013-05-05
    • 2011-08-18
    • 2013-06-28
    相关资源
    最近更新 更多