title: Java Mapping Mixed Types
body: <p>I am looking for a way to create a HashMap that maps to mixed types.</p>
  
  <p>For example, the following would work in Python (note that a Python <code>dict</code> is similar to a Java <code>HashMap</code>):</p>
  
  <pre><code>d = dict()
  d["str"] = "This is a string"
  d["flt"] = 1.23
  d["int"] = 5
  </code></pre>
  
  <p>and when accessing <code>d[x]</code>, the appropriate type would be returned (string, float, int in this example).</p>
  
  <p>In Java, I could go with a <code>HashMap&lt;String, Object&gt;</code>, but I don't really have a way to immediately tell what type each Object is.</p>
  
  <p>So instead, I'm currently trying to do is create a <code>MixedType</code> class that holds an object, but also its original type information, so that I can downcast it later.  For example:</p>
  
  <pre><code>public class MixedMap
      public static class MixedType
      {
          public Class&lt;?&gt; cls;
          public Object val;
  
          public MixedType(Class&lt;?&gt; c, Object v)
          {
              this.cls = c;
              this.val = v;
          }
      }
  
      public static void main(String args[])
      {   
          MixedType m1 = new MixedType(String.class, "This is a String");
          System.out.println((m1.cls)m1.val);
      }
  }
  </code></pre>
  
  <p>Note that this is what I'm <em>trying</em> to do :-)
  as it's currently not compiling complaining that <code>m1 cannot be resolved to a type</code>.</p>
  
  <p>So my question is, how can I fix this?  Other ways to achieve the same goal would be welcomed, but please don't answer telling me that this limits the type checking ability of the compiler -- I know that and am OK with it.</p>
  
  <p>Thanks in advance.</p>