title: HashMap adding object with equals true and same hashcode
body: <p>I am trying to create custom objects for <code>HashMap</code> and have written code for <code>hashcode</code> and <code>equals</code> method. While adding objects in <code>HashMap</code>, <code>equals</code> method is true and <code>hashcode</code> is returning same value for both objects yet <code>HashMap</code> is adding both objects as different objects. How can this be possible?
  Below is my code:</p>
  
  <pre><code>class B {
      String name;
      int id;
  
      public B(String name, int id)
      {
          this.name=name;
          this.id=id;
      }
  
      public boolean equals(B b){
          if(this==b)
              return true;
          if(b==null)
              return false;
          if(this.name.equals(b.name) &amp;&amp; this.id==b.id)
              return true;
          else
              return false;
      }
  
      public int hashcode(){
          return this.id;
      }
  
      public String toString(){
          return "name: "+name+" id: "+id;
      }
  }
  </code></pre>
  
  <p>For testing above code, I have added following in my main class:</p>
  
  <pre><code>HashMap&lt;B,String&gt; sample=new HashMap&lt;&gt;();
  B b1 = new B("Volga",1);
  B b2 = new B("Volga",1);
  System.out.println(b1.equals(b2));
  System.out.println(b1.hashcode()+"    "+b2.hashcode());
  sample.put(b1, "wrog");
  sample.put(b2,"wrog");
  System.out.println(sample);
  </code></pre>
  
  <p>This is producing following output:</p>
  
  <pre><code>true
  1    1
  {name: Volga id: 1=wrog, name: Volga id: 1=wrog}
  </code></pre>
  
  <p>Can someone please explain why is this happening?</p>