Java map get returns null

Java Map.get and Map.containsKey

When using Java’s Map implementations, it is sometimes common to invoke the Map ‘s get(Object) method and to react differently based on whether the value returned is null or not. A common assumption might be made that a null returned from Map.get(Object) indicates there is no entry with the provided key in the map, but this is not always the case. Indeed, if a Java Map implementation allows for null values, then it is possible for the Map to return its value for the given key, but that value might be a null. Often this doesn’t matter, but if it does, one can use Map.containsKey() to determine if the Map entry has a key entry. If it does and the Map returns null on a get call for that same key, then it is likely that the key maps to a null value. In other words, that Map might return «true» for containsKey(Object) while at the same time returning » null » for get(Object) . There are some Map implementations that do not allow null values. In those cases, a null from a «get» call should consistently match a «false» return from the «containsKey» method.

In this blog post, I demonstrate these aspects of Map.get(Object) and Map.containsKey(Object) . Before going into that demonstration, I will first point out that the Javadoc documentation for Map.get(Object) does explicitly warn about the subtle differences between Map.get(Object) and Map.containsKey(Object) :

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it’s also possible that the map explicitly maps the key to null . The containsKey operation may be used to distinguish these two cases.

For the post’s examples, I will be using the States enum defined next:

package dustin.examples; /** * Enum representing select western states in the United Sates. */ public enum States < ARIZONA("Arizona"), CALIFORNIA("California"), COLORADO("Colorado"), IDAHO("Idaho"), KANSAS("Kansas"), MONTANA("Montana"), NEVADA("Nevada"), NEW_MEXICO("New Mexico"), NORTH_DAKOTA("North Dakota"), OREGON("Oregon"), SOUTH_DAKOTA("South Dakota"), UTAH("Utah"), WASHINGTON("Washington"), WYOMING("Wyoming"); /** State name. */ private String stateName; /** * Parameterized enum constructor accepting a state name. * * @param newStateName Name of the state. */ States(final String newStateName) < this.stateName = newStateName; >/** * Provide the name of the state. * * @return Name of the state */ public String getStateName() < return this.stateName; >> 

The next code listing uses the enum above and populates a map of states to their capital cities. The method accepts a Class that should be the specific implementation of Map to be generated and populated.

Читайте также:  Выровнять html код pycharm

generateStatesMap(Class)

/** * Generate and populate a Map of states to capitals with provided Map type. * This method also logs any Map implementations for which null values are * not allowed. * * @param mapClass Type of Map to be generated. * @return Map of states to capitals. */ private static Map generateStatesMap(Class mapClass) < MapmapToPopulate = null; if (Map.class.isAssignableFrom(mapClass)) < try < mapToPopulate = mapClass != EnumMap.class ? (Map) mapClass.newInstance() : getEnumMap(); mapToPopulate.put(States.ARIZONA, "Phoenix"); mapToPopulate.put(States.CALIFORNIA, "Sacramento"); mapToPopulate.put(States.COLORADO, "Denver"); mapToPopulate.put(States.IDAHO, "Boise"); mapToPopulate.put(States.NEVADA, "Carson City"); mapToPopulate.put(States.NEW_MEXICO, "Sante Fe"); mapToPopulate.put(States.NORTH_DAKOTA, "Bismark"); mapToPopulate.put(States.OREGON, "Salem"); mapToPopulate.put(States.SOUTH_DAKOTA, "Pierre"); mapToPopulate.put(States.UTAH, "Salt Lake City"); mapToPopulate.put(States.WASHINGTON, "Olympia"); mapToPopulate.put(States.WYOMING, "Cheyenne"); try < mapToPopulate.put(States.MONTANA, null); >catch (NullPointerException npe) < LOGGER.severe( mapToPopulate.getClass().getCanonicalName() + " does not allow for null values - " + npe.toString()); >> catch (InstantiationException instantiationException) < LOGGER.log( Level.SEVERE, "Unable to instantiate Map of type " + mapClass.getName() + instantiationException.toString(), instantiationException); >catch (IllegalAccessException illegalAccessException) < LOGGER.log( Level.SEVERE, "Unable to access Map of type " + mapClass.getName() + illegalAccessException.toString(), illegalAccessException); >> else < LOGGER.warning("Provided data type " + mapClass.getName() + " is not a Map."); >return mapToPopulate; > 

The method above can be used to generate Maps of various sorts. I don’t show the code right now, but my example creates these Maps with four specific implementations: HashMap, LinkedHashMap, ConcurrentHashMap, and EnumMap. Each of these four implementations is then run through the method demonstrateGetAndContains(Map) , which is shown next.

demonstrateGetAndContains(Map)

/** * Demonstrate Map.get(States) and Map.containsKey(States). * * @param map Map upon which demonstration should be conducted. */ private static void demonstrateGetAndContains(final Map map)

For this demonstration, I intentionally set up the Maps to have null capital values for Montana to have no entry at all for Kansas. This helps to demonstrate the differences in Map.get(Object) and Map.containsKey(Object) . Because not every Map implementation type allows for null values, I surrounded the portion that puts Montana without a capital inside a try/catch block.

The results of running the four types of Maps through the code appears next.

Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet logMapInfo INFO: HashMap: Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet demonstrateGetAndContains INFO: Map of type java.util.HashMap returns null for Map.get() using Montana Map of type java.util.HashMap returns true for Map.containsKey() using Montana Map of type java.util.HashMap returns null for Map.get() using Kansas Map of type java.util.HashMap returns false for Map.containsKey() using Kansas Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet logMapInfo INFO: LinkedHashMap: Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet demonstrateGetAndContains INFO: Map of type java.util.LinkedHashMap returns null for Map.get() using Montana Map of type java.util.LinkedHashMap returns true for Map.containsKey() using Montana Map of type java.util.LinkedHashMap returns null for Map.get() using Kansas Map of type java.util.LinkedHashMap returns false for Map.containsKey() using Kansas Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet generateStatesMap SEVERE: java.util.concurrent.ConcurrentHashMap does not allow for null values - java.lang.NullPointerException Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet logMapInfo INFO: ConcurrentHashMap: Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet demonstrateGetAndContains INFO: Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Montana Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Montana Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Kansas Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Kansas Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet logMapInfo INFO: EnumMap: Aug 17, 2010 11:23:26 PM dustin.examples.MapContainsGet demonstrateGetAndContains INFO: Map of type java.util.EnumMap returns null for Map.get() using Montana Map of type java.util.EnumMap returns true for Map.containsKey() using Montana Map of type java.util.EnumMap returns null for Map.get() using Kansas Map of type java.util.EnumMap returns false for Map.containsKey() using Kansas 

For the three Map types for which I was able to input null values, the Map.get(Object) call returns null even when the containsKey(Object) method returns «true» for Montana because I did put that key in the map without a value. For Kansas, the results are consistently Map.get() returns null and Map.containsKey() returns «false» because there is no entry whatsoever in the Maps for Kansas.

The output above also demonstrates that I could not put a null value for Montana’s capital into the ConcurrentHashMap implementation (an NullPointerException was thrown).

SEVERE: java.util.concurrent.ConcurrentHashMap does not allow for null values — java.lang.NullPointerException

This had the side effect of keeping Map.get(Object) and Map.containsKey(Object) a more consistent respective null and false return values. In other words, it was impossible to have a key be in the map without having a corresponding non-null value.

In many cases, use of Map.get(Object) works as needed for the particular needs at hand, but it is best to remember that there are differences between Map.get(Object) and Map.containsKey(Object) to make sure the appropriate one is always used. It is also interesting to note that Map features a similar containsValue(Object) method as well.

I list the entire code listing for the MapContainsGet class here for completeness:

Источник

Interface Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two «standard» constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

The «destructive» methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be «superimposed» is empty.

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. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: «returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)) .» This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k . Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

Some map operations which perform recursive traversal of the map may fail with an exception for self-referential instances where the map directly or indirectly contains itself. This includes the clone() , equals() , hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

Unmodifiable Maps

  • They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method on the Map will always cause UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  • They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException .
  • They are serializable if all keys and values are serializable.
  • They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException .
  • The iteration order of mappings is unspecified and is subject to change.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Оцените статью