JDK-8222002 : get(null) on single-entry unmodifiable Map returns null instead of throwing NPE
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P3
  • Status: Closed
  • Resolution: Approved
  • Fix Versions: 13
  • Submitted: 2019-04-04
  • Updated: 2019-05-29
  • Resolved: 2019-04-06
Related Reports
CSR :  
Description
Summary
-------

An unmodifiable Map with one entry uses a different implementation that behaves inconsistently compared to those with zero or two or more entries. It is also inconsistent with other Map implementations that disallow nulls.

Problem
-------

Most operations on unmodifiable collections that involve null will throw NullPointerException. In particular, get(null) on an unmodifiable map with zero or two or more entries will throw NPE. On unmodifiable maps of all sizes, containsKey(null) and containsValue(null) throw NPE, and unmodifiable Lists and Sets throw NPE in response to contains(null). Other map implementations that disallow nulls, such as ConcurrentHashMap and Hashtable, throw NPE for all of these cases. The reason is that nulls are disallowed in these collections. Calling get(null) or contains*(null) is likely to be a programming error. If such methods were to return normally instead of throwing, it might let the error go undetected for longer.

Calling get(null) on a one-entry unmodifiable map returns null. This is clearly inconsistent with all of the above behaviors.

Solution
--------

The one-entry unmodifiable Map implementation should be changed to throw NPE in response to get(null). 

Specification
-------------

No specification change; this is a behavioral change only.

Comments
I haven't read the full review thread on core-libs. If such a testing effort is not already planned, I recommend a "scion of MOAT" (mother of all [collection] tests) test development effort to help flush out any remaining analogous issues. Moving to Approved.
06-04-2019