简体   繁体   中英

Why does the implementations of Map handle null differently?

Let's take the containsKey(Object key) as example:

  • TreeMap throws a NullPointerException if the key is null.
  • TreeMap returns false if there is no mapping for the key.
  • HashMap doesn't throw a NullPointerException and never returns null.

Lets have a look into the Javadoc for TreeSet:

Throws NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

Meaning: those two Map implementations really have different semantics. Therefore it makes sense that their individual implementations of "Map" methods do work differently.

One key property of TreeSet is the fact that it supports/requires ordering . That doesn't play nicely with null , thus it is "fair" to throw when null is coming in.

Just read the documentation here :

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM