Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement hashCode and equals method

How should I implement hashCode() and equals() for the following class in Java?

class Emp  {   int empid ; // unique across all the departments    String name;   String dept_name ;   String code ; // unique for the department  } 
like image 489
Vidya Avatar asked Jan 25 '10 12:01

Vidya


People also ask

How hashCode () and equals () method are used in HashMap?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.

What are the hashCode () and equal () functions?

internal consistency: the value of hashCode() may only change if a property that is in equals() changes. equals consistency: objects that are equal to each other must return the same hashCode. collisions: unequal objects may have the same hashCode.


2 Answers

in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this:

/* (non-Javadoc)  * @see java.lang.Object#hashCode()  */ @Override public int hashCode() {     final int prime = 31;     int result = 1;     result = prime * result + (code == null ? 0 : code.hashCode());     return result; } /* (non-Javadoc)  * @see java.lang.Object#equals(java.lang.Object)  */ @Override public boolean equals(Object obj) {     if (this == obj)         return true;     if (obj == null)         return false;     if (!(obj instanceof Emp))         return false;     Emp other = (Emp) obj;     return code == null ? other.code == null : code.equals(other.code); } 

I've selected code as a unique field

like image 120
jutky Avatar answered Sep 18 '22 15:09

jutky


try this code, use org.apache.commons.lang3.builder

public int hashCode() {     return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers         append(empid).         append(name).         append(dept_name ).         append(code ).         toHashCode(); }  public boolean equals(Object obj) {      if (obj == this)         return true;     if (!(obj instanceof Person))         return false;      Emp rhs = (Emp) obj;     return new EqualsBuilder().         // if deriving: appendSuper(super.equals(obj)).         append(name, rhs.name).         isEquals(); } 
like image 44
xingfe123 Avatar answered Sep 19 '22 15:09

xingfe123