Head-First-Design-Patterns
Head-First-Design-Patterns copied to clipboard
DinerMenuIterator.hasNext() does not handle null menu entries
hasNext() only checks whether position is within the array length and does not check whether the current menu entry is null.
DinerMenu uses a fixed-size array, so the menu can be partially populated. When there are unused slots, hasNext() can still return true for those slots, and next() can return null.
If the caller then tries to use the returned MenuItem, for example by calling getName(), this can result in a NullPointerException.
Please restore the null check in hasNext():
if (position >= items.length || items[position] == null) { return false; }
This ensures that unused array slots are not treated as valid menu items.