Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • 1) equals()
  • Without Equals :
  • 1.1) Overriding equals()
  • Genrating Equals/Hashcode using Eclipse:
  • With Equals :
  • https://stackoverflow.com/questions/596462/any-reason-to-prefer-getclass-over-instanceof-when-generating-equals
  • 1.2) equals() Contract
  • 1.3) Violating equals() Symmetry with Inheritance
  • 1.4) Way 1: Using getClass instead of instanceOf()
  • 1.4) Way 2 : Fixing equals() Symmetry with Composition
  • 2. hashCode()
  • 2.1) hashCode() Contract
  • 2.2) Violating the Consistency of hashCode() and equals()
  • 2.3) HashMap Key with an Inconsistent hashCode()
  • Example : collisions: unequal objects may have the same hashCode
  • 3. When Do We Override equals() and hashCode()?
  • 4. Implementation Helpers
  • 6. Verifying the Contracts
  • 7. Conclusion

Was this helpful?

5) Equals and Hashcode

PreviousApplicationsNextProblems

Last updated 6 years ago

Was this helpful?

1) equals()

The Object class defines both the equals() and hashCode() methods – which means that these two methods are implicitly defined in every Java class, including the ones we create:

We would expect income.equals(expenses) to return true. But with the Money class in its current form, it won’t.

The default implementation of equals() in the class Object says that equality is the same as object identity. And income and expenses are two distinct instances.

Without Equals :

package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class WrongMoney {
	int amount;
	String currencyCode;

	public WrongMoney() {
		super();
		// TODO Auto-generated constructor stub
	}

	public WrongMoney(int amount, String currencyCode) {
		super();
		this.amount = amount;
		this.currencyCode = currencyCode;
	}

}
package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class TestWrongMoney {
	public static void main(String[] args) {
		WrongMoney income = new WrongMoney(55, "USD");
		WrongMoney expenses = new WrongMoney(55, "USD");
		boolean balanced = income.equals(expenses);
		System.out.println("Are the equal :" + balanced);
	}

}

1.1) Overriding equals()

Let’s override the equals() method so that it doesn’t consider only object identity, but rather also the value of the two relevant properties:

Genrating Equals/Hashcode using Eclipse:

Way 1: Using getClass()

package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class Money {
	int amount;
	String currencyCode;

	public Money() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Money(int amount, String currencyCode) {
		super();
		this.amount = amount;
		this.currencyCode = currencyCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Money other = (Money) obj;
		if (amount != other.amount)
			return false;
		if (currencyCode == null) {
			if (other.currencyCode != null)
				return false;
		} else if (!currencyCode.equals(other.currencyCode))
			return false;
		return true;
	}

}

Way 2: Using instanceOf()

With Equals :

package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class Money {
	int amount;
	String currencyCode;

	public Money() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Money(int amount, String currencyCode) {
		super();
		this.amount = amount;
		this.currencyCode = currencyCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Money))
			return false;
		Money other = (Money) obj;
		if (amount != other.amount)
			return false;
		if (currencyCode == null) {
			if (other.currencyCode != null)
				return false;
		} else if (!currencyCode.equals(other.currencyCode))
			return false;
		return true;
	}

	

}
package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class TestMoney {
	public static void main(String[] args) {
		Money income = new Money(55, "USD");
		Money expenses = new Money(55, "USD");
		boolean balanced = income.equals(expenses);
		System.out.println("Are the equal :"+balanced);
	}
}

1.2) equals() Contract

Java SE defines a contract that our implementation of the equals() method must fulfill. Most of the criteria are common sense. The equals() method must be:

  • reflexive: an object must equal itself

  • symmetric: x.equals(y) must return the same result as y.equals(x)

  • transitive: if x.equals(y) and y.equals(z) then also x.equals(z)

  • consistent: the value of equals() should change only if a property that is contained in equals() changes (no randomness allowed)

1.3) Violating equals() Symmetry with Inheritance

If the criteria for equals() is such common sense, how can we violate it at all? Well, violations happen most often, if we extend a class that has overridden equals(). Let’s consider a Voucher class that extends our Money class:

At first glance, the Voucher class and its override for equals() seem to be correct. And both equals()methods behave correctly as long as we compare Money to Money or Voucher to Voucher. But what happens, if we compare these two objects?

That violates the symmetry criteria of the equals() contract.

package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class WrongVoucher extends Money {

	private String store;

	public WrongVoucher(String store) {
		super();
		this.store = store;
	}

	public WrongVoucher() {
		super();
		// TODO Auto-generated constructor stub
	}

	public WrongVoucher(int amount, String currencyCode, String store) {
		super(amount, currencyCode);
		this.store = store;
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (!(obj instanceof WrongVoucher))
			return false;
		WrongVoucher other = (WrongVoucher) obj;
		if (store == null) {
			if (other.store != null)
				return false;
		} else if (!store.equals(other.store))
			return false;
		return true;
	}
}
package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class TestWrongVoucher {
	public static void main(String[] args) {
		Money cash = new Money(42, "USD");
		WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");

		System.out.println(voucher.equals(cash));
		System.out.println(cash.equals(voucher));
	}
}

1.4) Way 1: Using getClass instead of instanceOf()

Refer to Way 1: Using getClass()

Example 2:

1.4) Way 2 : Fixing equals() Symmetry with Composition

To avoid this pitfall, we should favor composition over inheritance.

Instead of subclassing Money, let’s create a Voucher class with a Money property:

And now, equals will work symmetrically as the contract requires.

2. hashCode()

hashCode() returns an integer representing the current instance of the class. We should calculate this value consistent with the definition of equality for the class. Thus if we override the equals() method, we also have to override hashCode().

2.1) hashCode() Contract

Java SE also defines a contract for the hashCode() method. A thorough look at it shows how closely related hashCode() and equals() are.

All three criteria in the contract of hashCode() mention in some ways the equals() method:

  • 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.2) Violating the Consistency of hashCode() and equals()

The 2nd criteria of the hashCode methods contract has an important consequence: If we override equals(), we must also override hashCode(). And this is by far the most widespread violation regarding the contracts of the equals() and hashCode() methods.

Let’s see such an example:

The Team class overrides only equals(), but it still implicitly uses the default implementation of hashCode() as defined in the Object class. And this returns a different hashCode() for every instance of the class. This violates the second rule.

Now if we create two Team objects, both with city “New York” and department “marketing”, they will be equal, but they will return different hashCodes.

2.3) HashMap Key with an Inconsistent hashCode()

But why is the contract violation in our Team class a problem? Well, the trouble starts when some hash-based collections are involved. Let’s try to use our Team class as a key of a HashMap:

We would expect myTeamLeader to return “Anne”. But with the current code, it doesn’t.

If we want to use instances of the Team class as HashMap keys, we have to override the hashCode()method so that it adheres to the contract: Equal objects return the same hashCode.

Let’s see an example implementation:

Example : collisions: unequal objects may have the same hashCode

package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class Doctor {
	private String fName;
	private String lName;

	/**
	 * @param fName
	 * @param lName
	 */
	public Doctor(String fName, String lName) {
		this.fName = fName;
		this.lName = lName;
	}

	@Override
	public int hashCode() {
		int result = fName.hashCode() + lName.hashCode();
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Doctor other = (Doctor) obj;
		if (fName == null) {
			if (other.fName != null)
				return false;
		} else if (!fName.equals(other.fName))
			return false;
		if (lName == null) {
			if (other.lName != null)
				return false;
		} else if (!lName.equals(other.lName))
			return false;
		return true;
	}

}
package com.gs.ilp.corejava.collectionsFramework2.equalsandhashcode;

public class TestDoctorHashcodeRule3 {
	public static void main(String[] args) {
		Doctor doctor1 = new Doctor("Mohit", "Vijay");
		Doctor doctor2 = new Doctor("Vijay", "Mohit");
		System.out.println(
				"Doctors having different objects with different values but they still can have same hashcode");
		System.out.println("Are they equal " + doctor1.equals(doctor2));
		System.out.print("Do the have same hashcode ");
		if (doctor1.hashCode() == doctor2.hashCode()) {
			System.out.println(true);
		} else {
			System.out.println(false);
		}
		System.out.println("Hashcode of doctor 1 " + doctor1.hashCode());
		System.out.println("Hashcode of doctor 2 " + doctor2.hashCode());
	}

}

3. When Do We Override equals() and hashCode()?

Generally, we want to override either both of them or neither of them. We’ve just seen in Section 3 the undesired consequences if we ignore this rule.

Domain-Driven Design can help us decide circumstances when we should leave them be. For entity classes – for objects having an intrinsic identity – the default implementation often makes sense.

However, for value objects, we usually prefer equality based on their properties. Thus want to override equals() and hashCode(). Remember our Money class from Section 1: 55 USD equals 55 USD – even if they’re two separate instances.

4. Implementation Helpers

We typically don’t write the implementation of these methods by hand. As can be seen, there are quite a few pitfalls.

One common way is to let our IDE generate the equals() and hashCode() methods.

Apache Commons Lang and Google Guava have helper classes in order to simplify writing both methods.

Project Lombok also provides an @EqualsAndHashCode annotation. Note again how equals() and hashCode() “go together” and even have a common annotation.

6. Verifying the Contracts

If we want to check whether our implementations adhere to the Java SE contracts and also to some best practices, we can use the EqualsVerifier library.

Let’s verify that our Team class follows the equals() and hashCode() contracts:

It’s worth noting that EqualsVerifier tests both the equals() and hashCode() methods.

EqualsVerifier is much stricter than the Java SE contract. For example, it makes sure that our methods can’t throw a NullPointerException. Also, it enforces that both methods, or the class itself, is final.

It’s important to realize that the default configuration of EqualsVerifier allows only immutable fields. This is a stricter check than what the Java SE contract allows. This adheres to a recommendation of Domain-Driven Design to make value objects immutable.

If we find some of the built-in constraints unnecessary, we can add a suppress(Warning.SPECIFIC_WARNING) to our EqualsVerifier call.

7. Conclusion

We should remember to:

  • Always override hashCode() if we override equals()

  • Override equals() and hashCode() for value objects

  • Be aware of the traps of extending classes that have overridden equals() and hashCode()

  • Consider using an IDE or a third-party library for generating the equals() and hashCode() methods

  • Consider using EqualsVerifier to test our implementation

We can look up the exact criteria in the .

For some more details, check out our .

Let’s add the Maven test dependency:

Finally, all code examples can be found .

https://stackoverflow.com/questions/596462/any-reason-to-prefer-getclass-over-instanceof-when-generating-equals
Java SE Docs for the Object class
guide to hashCode()
EqualsVerifier
over on GitHub
LogoJava - equals method in base class and in subclassesStack Overflow