What is the Java hashCode Method?

Java Conceptuel Diagram

About

The Java hashCode method outputs a hash creating an unique identifier for the object.

If two objects are equal, they must have the same hashCode() output.

The hashCode is generally overwritten by the developer to be an output of the natural identifier.

When the hashCode method is implemented, the equal method is also implemented to enable the equality of objects.

Example

@Override
public int hashCode() {
   return Objects.hash(firstId, secondId);
}

Utility

org.apache.commons.lang.builder

package org.apache.commons.lang.builder;
HashCodeBuilder builder = new HashCodeBuilder(17, 37);

builder.append(name);
if (table!=null){
	//TODO: May be implementation of an URI for each database object
	builder.append(table.getName());
	builder.append(table.getSchemaObject().getName());
	builder.append(table.getSchemaObject().getCatalog().getName());
	builder.append(table.getSchemaObject().getCatalog().getPlatform().getName());
}

		
return builder.toHashCode();





Discover More
Java Conceptuel Diagram
What does the equals method in Java?

The equals method is the the equality operator. hashCode() . In a set implementation, it's used to be sure that there will be no duplicate objects.



Share this page:
Follow us:
Task Runner