Tuesday, August 17, 2010

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:

States.java
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.

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<States, String> generateStatesMap(Class mapClass)
   {
      Map<States,String> mapToPopulate = null;
      if (Map.class.isAssignableFrom(mapClass))
      {
         try
         {
            mapToPopulate =
               mapClass != EnumMap.class
               ? (Map<States, String>) 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<states,string>)
/**
    * Demonstrate Map.get(States) and Map.containsKey(States).
    *
    * @param map Map upon which demonstration should be conducted.
    */
   private static void demonstrateGetAndContains(final Map<States, String> map)
   {
      final StringBuilder demoResults = new StringBuilder();
      final String mapType = map.getClass().getCanonicalName();

      final States montana = States.MONTANA;
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.get(montana)) + " for Map.get() using " + montana.getStateName());
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.containsKey(montana)) + " for Map.containsKey() using "
         + montana.getStateName());
      demoResults.append(NEW_LINE);

      final States kansas = States.KANSAS;
      demoResults.append(
            "Map of type " + mapType + " returns "
         + (map.get(kansas)) + " for Map.get() using " + kansas.getStateName());
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.containsKey(kansas)) + " for Map.containsKey() using "
         + kansas.getStateName());
      demoResults.append(NEW_LINE);
      LOGGER.info(demoResults.toString());
   }

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: {MONTANA=null, WASHINGTON=Olympia, ARIZONA=Phoenix, CALIFORNIA=Sacramento, WYOMING=Cheyenne, SOUTH_DAKOTA=Pierre, COLORADO=Denver, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, NEVADA=Carson City, OREGON=Salem, UTAH=Salt Lake City, IDAHO=Boise}
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: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne, MONTANA=null}
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: {SOUTH_DAKOTA=Pierre, ARIZONA=Phoenix, WYOMING=Cheyenne, UTAH=Salt Lake City, OREGON=Salem, CALIFORNIA=Sacramento, IDAHO=Boise, NEW_MEXICO=Sante Fe, COLORADO=Denver, NORTH_DAKOTA=Bismark, WASHINGTON=Olympia, NEVADA=Carson City}
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: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, MONTANA=null, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne}
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).


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


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:

MapContainsGet.java
package dustin.examples;

import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Simple example of using Map.get(key) versus Map.containsKey(key).
 */
public class MapContainsGet
{
   /** Handle to java.util.logging Logger. */
   private static Logger LOGGER = Logger.getLogger("dustin.examples.MapContainsGet");

   /** New line. */
   private static final String NEW_LINE = System.getProperty("line.separator");

   /**
    * 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<States, String> generateStatesMap(Class mapClass)
   {
      Map<States,String> mapToPopulate = null;
      if (Map.class.isAssignableFrom(mapClass))
      {
         try
         {
            mapToPopulate =
               mapClass != EnumMap.class
               ? (Map<States, String>) 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;
   }

   /**
    * Provide the {@code Map<States, String>} as an EnumMap.
    *
    * @return EnumMap of States to String.
    */
   private static EnumMap<States, String> getEnumMap()
   {
      return new EnumMap<States, String>(States.class);
   }

   /**
    * Log the provided Map and its type.
    *
    * @param mapToLog Map to have its type and content logged.
    */
   private static void logMapInfo(final Map<States, String> mapToLog)
   {
      LOGGER.info(
           mapToLog != null
         ? (mapToLog.getClass().getSimpleName() + ": " + mapToLog.toString())
         : "null Map");      
   }

   /**
    * Demonstrate Map.get(States) and Map.containsKey(States).
    *
    * @param map Map upon which demonstration should be conducted.
    */
   private static void demonstrateGetAndContains(final Map<States, String> map)
   {
      final StringBuilder demoResults = new StringBuilder();
      final String mapType = map.getClass().getCanonicalName();

      final States montana = States.MONTANA;
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.get(montana)) + " for Map.get() using " + montana.getStateName());
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.containsKey(montana)) + " for Map.containsKey() using "
         + montana.getStateName());
      demoResults.append(NEW_LINE);

      final States kansas = States.KANSAS;
      demoResults.append(
            "Map of type " + mapType + " returns "
         + (map.get(kansas)) + " for Map.get() using " + kansas.getStateName());
      demoResults.append(NEW_LINE);
      demoResults.append(
           "Map of type " + mapType + " returns "
         + (map.containsKey(kansas)) + " for Map.containsKey() using "
         + kansas.getStateName());
      demoResults.append(NEW_LINE);
      LOGGER.info(demoResults.toString());
   }

   /**
    * Main executable function.
    *
    * @param arguments Command-line arguments; none expected.
    */
   public static void main(final String[] arguments)
   {
      final Map<States, String> hashMap = generateStatesMap(HashMap.class);
      logMapInfo(hashMap);
      demonstrateGetAndContains(hashMap);
      final Map<States, String> linkedHashMap = generateStatesMap(LinkedHashMap.class);
      logMapInfo(linkedHashMap);
      demonstrateGetAndContains(linkedHashMap);
      final Map<States, String> concurrentHashMap = generateStatesMap(ConcurrentHashMap.class);
      logMapInfo(concurrentHashMap);
      demonstrateGetAndContains(concurrentHashMap);
      final Map<States, String> enumMap = generateStatesMap(EnumMap.class);
      logMapInfo(enumMap);
      demonstrateGetAndContains(enumMap);
   }
}

I used an enum as the key for this demonstration which was nice because of its satisfactory equals and hashCode implementations available immediately with no extra effort on my part.  Objects used as keys without these set properly can misbehave in general and cause other differences between Map.get(Object) and Map.containsKey(Object) in certain cases.

No comments: