Search code examples
javadictionaryprimitiveword-wrap

Java Mappings and Primitives


I want to create a mapping that takes a String as the key and a primitive as the value. I was looking at the Java docs and did not see that Primitive was a class type, or that they shared some kind of wrapping class.

How can I constrain the value to be a primitive?

Map<String, Primitive> map = new HashMap<String, Primitive>();


Solution

  • Java Autoboxing allows to create maps on Long, Integer, Double and then operate them using primitive values. For example:

    java.util.HashMap<String, Integer> map = new java.util.HashMap<String, Integer>();
    map.put("one", 1); // 1 is an integer, not an instance of Integer
    

    If you want to store in one map different primitive types, you can to it by making a Map<String, Number>. Allows to store values of BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short (and AtomicLong, AtomicInteger).

    Here is an example:

    Map<String, Number> map = new HashMap<String, Number>();
    
    map.put("one", 1);
    map.put("two", 2.0);
    map.put("three", 1L);
    
    for(String k:map.keySet()) {
      Number v = map.get(k);
      System.err.println(v + " is instance of " + v.getClass().getName() + ": " + v);
    }