How to use Java HashMap and IdentityHashMap?
<p>I am using HashMap.</p>

<p>Below is example code.</p>

<p>Classes MyKey and MyValue are inhereted from Object in simple way.</p>

<p>Java documentation says for Object and methods hashCode() and equals():</p>

<p>"As much as is reasonably practical, the hashCode method defined
by class Object does return distinct integers for distinct objects.
(This is typically implemented by converting the internal address
of the object into an integer, but this implementation technique
is not required by the JavaTM programming language.)"</p>

<p>"The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null reference
values x and y, this method returns true if and only if x and y refer
to the same object (x == y has the value true). "</p>

<p>My question is:</p>

<p>Can I trust that HashMap works in my example?
If not what would be right way to put simple objects into map without rewriting methods
hashCode() and equals()?</p>

<p>I am not sure but I have heard that Java may change location and addresss
of user objects during execution of program (Was it GC which may do that?)</p>

<p>If address and hash code of key2 have changed before the line</p>

<pre><code>    MyValue v = m.get(key2);
</code></pre>

<p>then calling m.get(key2) would return wrong value, null?</p>

<p>If this is true then I believe that also IdentityHashMap()
is useless for same reasons. </p>

<pre><code>class MyKey
{
  Integer v;
  //&lt;Perhaps more fields&gt;
  MyKey(Integer v) {this.v=v;}
}

class MyValue
{
  String s;
  //&lt;Perhaps more fields&gt;
  MyValue(String s) {this.s = s;}
}


Then some code:

Map&lt;MyKey,MyValue&gt; m = new HashMap&lt;MyKey,MyValue&gt;();

MyKey key1 = new MyKey(5);
MyKey key2 = new MyKey(6);
MyKey key3 = new MyKey(7);


m.put(key1, new MyValue("AAA"));
m.put(key2, new MyValue("BBB"));
m.put(key3, new MyValue("CCC"));

.
.

//Is it sure that I will get value "AAA" here
//if entry with key2 has not been removed from map m?
MyValue v = m.get(key2);
System.out.println("s="+v.s);
</code></pre>
