Vikash Mishra Vikash Mishra - 1 month ago 4x
Java Question

Output of hashmap

Till now I was very much clear about hashmap internal working.But seeing the below snippet of code I am little bit confused.

In the following code, my class's

method always returns false. Therefore I would expect
to never find a key of that class.

Can someone please explain me. In the get method I know it will calculate the hashcode and it will find the exact bucket but as equals is returning false how can it return 3?

package com.vikash.Theory.CollectionsFramework;

public class Emp {

private String firstName;
private String lastName;

public Emp(String firstName,String lastName) {

public String getFirstName() {
return firstName;

public void setFirstName(String firstName) {
this.firstName = firstName;

public String getLastName() {
return lastName;

public void setLastName(String lastName) {
this.lastName = lastName;

public int hashCode() {
return firstName.hashCode()+lastName.hashCode();

public boolean equals(Object o) {
return false;

public class Test {

public static void main(String[] args) {

Map<Object,Integer> map=new HashMap<Object,Integer>();
Emp e1=new Emp("Vikash","Mishra");
Emp e2=new Emp("Mishra","Vikash");
Emp e3=new Emp("Mishra","Vikash");
map.put(e1, 1);
map.put(e2, 2);
map.put(e3, 3);
System.out.println("Size of the map is:"+map.size());
System.out.println(map.get(e3)); } }


The source code of HashMap reveals all:

322      if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
323                 return e.value;

It tests for e.key == key before it tests for key.equals(e.key).

In general, having a buggy equals() causes all kinds of confusing behaviour in Java, so it's very wise to avoid doing so. One part of the equals() contract is that x.equals(x) should always be true.