What Is the Use of Hashcode in Java

What is the purpose of hashcode method in java?

You must always override equals and hashCode in tandem, to satisfy their interdependent contracts. A class which implements them contradictorily is simply broken and unacceptable under even the minimum software engineering standards.

As to why one would ever use the hashtable data structure: because it is the fastest option around for random-access key-value storage.

hashCode() method

Suppose you have a class with two String fields, and that its hashcode is calculated by summing the hashcodes of those two fields. Further suppose you have an equals that simply checks whether the class fields values are equal.

class Test {
String a;
String b;

public Test

@Override
public int hashCode() {
return a.hashCode() + b.hashCode();
}

@Override
public boolean equals(Object o) { // simplified
Test other = (Test)o;
return a.equals(other.a) && b.equals(other.b);
}
}

Let's see if non-equal instances can have the same hashcode

Test t1 = new Test("hello", "world");
Test t2 = new Test("world", "hello");

System.out.println(t1.equals(t2)); // false
System.out.println(t1.hashCode() == t2.hashCode()); // true

Are we still respecting hashCode's contract?

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

Well, yes, since it only depends on a and b and we're using their hashCode method which we can assume respects the contract.

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It does

Test t1 = new Test("hello", "world");
Test t2 = new Test("hello", "world");

System.out.println(t1.equals(t2)); // true
System.out.println(t1.hashCode() == t2.hashCode()); // true

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

That's what we were trying to demonstrate in the first place. It's not a requirement.

What is the purpose of having hashCode in Optional

It allows you to store Optionals (whose value types also override equals and hashCode) in HashSets and use them as keys in HashMaps.

If Optional didn't override equals and hashCode, the following code would output 2 instead of 1:

Map<Optional<String>,String> map = new HashMap<>();
map.put(Optional.of("someKey"),"someValue");
map.put(Optional.of("someKey"),"someOtherValue");
System.out.println(map.size());

What is the use of hashcode in Document Snapshot?

This method isn't intended to be used as a way of identifying if two document snapshots are the same. It's not really part of the API surface that developers use directly. You should probably just ignore it completely unless you have a specific problem with it.

hashCode here has the same purpose that any subclass of Object would use for hashCode. From the API docs:

This method is supported for the benefit of hash tables such as those provided by HashMap.

This implementation lets the DocumentSnapshot object work well with HashMap or other collections that require a hashCode implementation. You can trust that it works fine. If you think there is a bug or problem here that you can duplicate, then file a bug on GitHub with your observations.

Is it recommended to use hashcode to determine equality in Java?

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;
}

}

Why does Java need equals() if there is hashCode()?

If two objects have the same hashCode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function. But the opposite is true - if the objects are equal, then they must have the same hashCode.

hashCode() purpose in Java

I like Jon Skeet's answer (+1) but it requires knowing how hash tables work. A hash table is a data structure, basically an array of buckets, that uses the hashcode of the key to decide which bucket to stick that entry in. That way future calls to retrieve whatever's at that key don't have to sift through the whole list of things stored in the hashtable, the hashtable can calculate the hashcode for the key, then go straight to the matching bucket and look there. The hashcode has to be something that can be calculated quickly, and you'd rather it was unique but if it isn't it's not a disaster, except in the worst case (your return 42;), which is bad because everything ends up in the same bucket and you're back to sifting through everything.

The default value for Object#hashCode may be based on something like a memory location just because it's a convenient sort-of-random number, but as the object is shunted around during memory management that value is cached and nobody cares anyway. The hashcodes created by different objects, like String or BigDecimal, certainly have nothing to do with memory. It's just a number that is quickly generated and that you hope is unique more often than not.

how does the hashCode() method of java works?

Java doesn't generate hashCode(), i.e. nothing automatic is happening here. However, Object generates a HashCode based on the memory address of the instance of the object. Most classes (especially if you are going to use it in any of the Collection API) should implement their own HashCode (and by contract their own equals method).



Related Topics



Leave a reply



Submit