Note that there are some explanatory texts on larger screens.

plurals
  1. PODifferent hashcode but HashMap not working
    text
    copied!<p>I have a class <code>myDemoClass</code> to store name and a class to put in a <code>HashMap</code>. While experimenting with overriding <code>hashCode()</code> method, the <code>HashMap</code> is returning <code>null</code> even if hashcodes are different. Why? I have overridden the <code>hashCode()</code> method so that different objects will have different hashcode even if having the same name value.</p> <pre><code>public class myDemoClass { String name; int value; static int i=1; public String getName() { return name; } public void setName(String name) { this.name = name; } public int hashCode() { //return name.hashCode();//now the hashcode are same return i++;//now the hashcode is different } public boolean equals(Object obj) { myDemoClass m=(myDemoClass)obj; if(obj==this) return true; if(obj instanceof myDemoClass) { return getName().equals(m.getName()); } return false; } } </code></pre> <p></p> <pre><code>public class Hashcodes { myDemoClass m1=new myDemoClass(); myDemoClass m2=new myDemoClass(); HashMap h=new HashMap(); public boolean test() { m1.setName("s"); m2.setName("s"); System.out.println(m1.hashCode()); System.out.println(m2.hashCode()); h.put(m1, "a1"); h.put(m1, "b1"); System.out.println(h.get(m1)); System.out.println(h.get(m2)); System.out.println(h.get(m1)); return true; } public static void main(String args[]) { Hashcodes h=new Hashcodes(); h.test(); } } </code></pre> <p>Output with different hashcode:</p> <pre class="lang-none prettyprint-override"><code>1 2 null null null </code></pre> <p>Output with same hashcode:</p> <pre class="lang-none prettyprint-override"><code>115 115 b1 b1 b1 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload