What are common mistakes developers make with enhanced for-each loop?

Developers often use the enhanced for-each loop in Java to iterate over collections and arrays for its simplicity and readability. However, there are some common mistakes that can lead to performance issues or incorrect behavior. Below are some key mistakes to watch out for:

  • Modification of the Collection: Modifying a collection while iterating over it can lead to ConcurrentModificationException.
  • Null Collections: Attempting to loop over a null collection will result in a NullPointerException.
  • Type Safety: Using raw types instead of generics can lead to ClassCastException at runtime.
  • Looping Over Unmodifiable Collections: Attempting to add or remove elements in an unmodifiable collection can also cause exceptions.

It's essential to be aware of these pitfalls while utilizing the enhanced for-each loop to ensure your code is robust and error-free.

Here’s an example of a naive mistake using the enhanced for-each loop:

// Example of incorrect usage of the enhanced for-each loop in Java List items = new ArrayList<>(Arrays.asList("A", "B", "C")); for (String item : items) { if ("B".equals(item)) { items.remove(item); // This will throw ConcurrentModificationException } }

enhanced for-each loop Java common mistakes loop pitfalls ConcurrentModificationException