title: How do I use a foreach loop in Java to loop through the values in a HashMap?
body: <p>I am trying to compile the following code:</p>
  
  <pre><code>private String dataToString(){
      Map data = (HashMap&lt;MyClass.Key, String&gt;) getData();
      String toString = "";
      for( MyClass.Key key: data.keySet() ){
          toString += key.toString() + ": " + data.get( key );
      return toString;
  }
  </code></pre>
  
  <p>I get an error in the for line that says:</p>
  
  <pre>
  incompatible types
  found : java.lang.Object
  required: MyClass.Key
  </pre>
  
  <p>The <code>getData()</code> method returns an <code>Object</code> (but in this case the <code>Object</code> returned has the <code>HashMap</code> structure).  <code>MyClass.Key</code> is an enum that I have created for the purposes of my application (in another class file - <code>MyClass</code>).</p>
  
  <p>When I created a foreach loop with the same structure in <code>MyClass.java</code>, I did not encounter this problem.</p>
  
  <p>What am I doing wrong?</p>