Head-First-Design-Patterns icon indicating copy to clipboard operation
Head-First-Design-Patterns copied to clipboard

DinerMenuIterator.hasNext() does not handle null menu entries

Open prashantpiyush1111 opened this issue 3 months ago • 0 comments

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.

prashantpiyush1111 avatar Aug 26 '26 18:08 prashantpiyush1111