I do not understand why a java.lang.NullPointerException is thrown with the following code (at this line: iterator = chapterKeywords[z].iterator();):
Iterator<String> iterator;
for (int z = 0; z < chapterKeywords.length; z++) {
try {
iterator = chapterKeywords[z].iterator();
//exception thrown here after first iteration (i.e., when z = 1) and subsequent ones
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
;
}
}
Although I get the NullPointerException, the code fully executes. FYI, chapterKeywords is a LinkedList Array where each array element is a LinkedList (e.g., singleChapterKeywords).
LinkedList<String>[] chapterKeywords = new LinkedList[numFiles];
LinkedList<String> singleChapterKeywords = new LinkedList<String>();
Although the program seems to run fine, I would like to understand why the NullPointerException is thrown as I would like to completely eliminate it. Basically, the exception is thrown at the start of each iteration in the for-loop. I’ve modified the code to create a new iterator inside the loop, create an array of iterators, etc but they all yield the same result: NullPointerException at iterator = chapterKeywords[z].iterator();.
Any help or insight into eliminating this exception is greatly appreciated.
So, here are my questions:
Why is there a NullPointerException thrown at each subsequent iteration when the iterator variable is being assigned to a new iterator?
How can I eliminate this exception?
Once again, TIA!
Update: I thought that the LinkedList’s were properly populated and worked fine, but, alas, this was not the case! Thank you all for your immeasurable help!
Looks like you’ve populated the lists but missed to add (some of) them to the array.
This will reveal your problem: