Java HashMap key comparison against string fails
<p>I have the following situation. I have a HashMap in Java with keys as strings.
Then in some stage , in runtime I create strings equal to those keys in order to retrieve the data from that map.The strings are created as follows within "for" loop:</p>

<pre><code> String keyToRetrive = "lights[" + Integer.toString(i) + "]" + ".Intensity";
</code></pre>

<p>The strange thing about it that when I iterate through the map to find the key that equals that string ,even when the match is found the search steps over.So in this search loop :</p>

<pre><code>  while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        if (name == entry.getKey()) {  ///name- "lights[0].Intesity"
            uniformOut = (ICleanable) entry.getValue();
            break;
        }
    }
</code></pre>

<p>The key with the name "lights[0].Intesity" never returns true even that the map contains one.How I solved it .I used hashCode() for both compared string values.So this version does work:</p>

<pre><code> while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        if (name.hashCode() == entry.getKey().hashCode()) {
            uniformOut = (ICleanable) entry.getValue();
            break;
        }
    }
</code></pre>

<p>UPDATE: After being pointed to the fact that  "==" doesn't work good and "equals()" should be used I would like to narrow the question:Why "==" does work for strings which were not created from several concatenated blocks? I mean, if I defines key string to compare agains as a simple single string:</p>

<pre><code> String foo="foo";
</code></pre>

<p>Such a string is compared using "==" against HashMap key all right.</p>

<p>I am not an expert Java programmer so can anybody explain why it works this way? </p>
