Amol Amol -5 years ago 98
Java Question

is hashcode() required only in case of class objects?

I am trying to understand

. I have 2 scenarios

1) implementing
with employee2 class objects

2) implementing
with primitives(though they are not primitives)

In case of class objects i understand that if i don't implement
it generates a random hashcode() every time , so when i retrieve the object , it looks into some different bucket each time and return NULL

But why dosen't this happen in the 2nd case when i don't use class objects

code is as follows:

package programs;
import java.util.*;

public class employee2
private int empid;
private String name;
private String dept;
public employee2(int empid,String name,String dept){
int getEmpid(){
return this.empid;
@Override public boolean equals(Object o){
employee2 e=(employee2)o;
return getEmpid()==e.empid;

@Override public int hashCode() {
int hash = 7;
hash = 83 * hash + this.empid;
return hash;
@Override public String toString(){
return empid+", "+name;

public static void main(String args[]){
//HashMap with employee class objects
Map<employee2,String> emap=new HashMap<>();
emap.put(new employee2(98446,"Amol Singh","Science"),"good");
emap.put(new employee2(98446,"Robin Singh","Math"),"very good");

// I get null if i dont override hashcode()
System.out.println(emap.get(new employee2(98446,"Robin Singh","Math")));

// New HashMap without Class objects
Map<Integer,String> emap2=new HashMap<>();

// I get correct answer without overriding hashcode()

Answer Source

Hash-based collections require hashCode to be overriden.

If you don't override it, they won't work fine.

Integer has it's own hashCode implementation, so you don't have to do anything when working with it in collections.

But you have to do this with the classes thay you create, if they are to be placed in hash-based collections

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download