Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it recommended to use hashcode to determine equality in Java? [duplicate]

Let's say we have a hashcode() function, which will then be used inside our equals() method to determine the equality of two objects. Is this an allowed/accepted approach?

Assume that we use a simple implementation of a hash code. (For example a few instance variables multiplied by prime numbers.)

like image 221
k4kuz0 Avatar asked Dec 28 '15 08:12

k4kuz0


1 Answers

This is a terrible way to check for equality, mostly since Objects don't have to be equal to return the same hashcode.

You should always use the equals method for this.

The general rule is:

If the equals method returns true for Objects a and b, the hashCode method must return the same value for a and b.

This does not mean, that if the hashCode method for a and b returns the same value, the equals method has to return true for these two instances.

for instance:

public int hashCode(){
  return 5;
}

is a valid, though be it inefficiënt, hashcode implementation.

EDIT:

to use it within an equals method would be something like this:

public class Person{

private String name;

public Person(String name){ this.name = name;}

public String getName(){ return this.name;}

@Override
public boolean equals(Object o){
  if ( !(o instanceof Person)){ return false;}
  Person p = (Person)o;
  boolean nameE = this.name == null ? p.getName() == null : this.name.equals(p.getName());
  boolean hashE = nameE ? true : randomTrueOrFalse();
  // the only moment you're sure hashE is true, is if the previous check returns true.
  // in any other case, it doesn't matter whether they are equal or not, since the nameCheck returns false, so in best case, it's redundant
  return nameE && hashE;
}

@Override
public int hashCode(){
  int hash = generateValidHashCode();
  return hash;
}

}
like image 200
Stultuske Avatar answered Oct 24 '22 15:10

Stultuske