【发布时间】: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<>();charCounts.put(i,curCounts)}... -
在调用
processLine之前,你是在调用你的方法DigitCount吗? -
@user3723352 不是
initialize,而是declare变量curCounts作为ArrayListo 类型Integer。初始化意味着,创建一个该类型的新对象,即ArrayList<Integer> curCounts = new ArrayList <Integer>();
标签: java arraylist nullpointerexception hashmap