Question
What causes NullPointerException in a LinkedList when iterating with a for-each loop?
List<String> list = null;
for (String item : list) {
System.out.println(item);
}
Answer
A NullPointerException in a LinkedList during iteration with a for-each loop indicates that the list is not properly initialized. This exception occurs when the code tries to iterate over an object that is null instead of a valid collection.
// Example of initializing and checking for null
LinkedList<String> list = new LinkedList<>(); // Properly initialize your LinkedList
list.add("First");
list.add("Second");
// Iterate safely
for (String item : list) {
System.out.println(item);
}
Causes
- The LinkedList has not been initialized (set to null).
- The LinkedList was cleared or not properly assigned before the for-each loop is called.
- Using a method that returns a null LinkedList.
Solutions
- Ensure that the LinkedList is initialized before using it. For example, use `LinkedList<String> list = new LinkedList<>();`.
- Check the source of the LinkedList and ensure that it is not null before the iteration begins.
- If the LinkedList can be null, consider using an if-statement to prevent iteration: `if (list != null) { ... }`.
Common Mistakes
Mistake: Neglecting to check if the LinkedList is initialized before usage.
Solution: Always initialize the LinkedList or check for null before the for-each loop.
Mistake: Clearing the list inadvertently and trying to iterate after that.
Solution: Ensure that the list has elements before iteration.
Helpers
- NullPointerException
- LinkedList
- for-each loop
- Java
- error handling
- common programming errors