DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • From Data Movement to Local Intelligence: The Shift from Centralized to Federated AI
  • Chaos Engineering Has a Blind Spot. Agentic AI Lives in It.
  • No More Cheap Claude: 4 First Principles of Token Economics in 2026
  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  1. DZone
  2. Coding
  3. Languages
  4. Identity Vs. Equality in Java

Identity Vs. Equality in Java

Take a quick look at identity and equality in Java, what they are, and how they compare to one another.

By 
Attila Mihaly user avatar
Attila Mihaly
·
Dec. 17, 19 · Presentation
Likes (4)
Comment
Save
Tweet
Share
30.6K Views

Join the DZone community and get the full member experience.

Join For Free

Let's take a quick look at identity and equality in Java, what they are, and how they compare to one another. 


You may also like: Object Identity and Equality in Java

Key Takeaways

  • Do not include ID fields in your Java domain classes.
  • Use all fields in your equals() and hashCode() implementation.

Explanation

I've seen a lot of Java code where developers implement equals() and hashCode() in terms of an ID field or a subset of fields that form a composite key. It's done so frequently that it becomes a pattern when, in my opinion, it is actually an anti-pattern. To understand why it's an anti-pattern, we have to differentiate identity from equality:

Identity

When we talk about identity in computer science, we usually think of something that uniquely identifies a person or thing. In Java, we use references to uniquely identify objects. This is also called referential equality (yes, the naming is confusing). You use == to compare the identities of two objects.

Notice that identity is something external. A reference is not part of the object it simply points to the object. Another important point is identity doesn't change over time: As I get older, I'm going through a lot of changes, but I'm still the same person. 

Equality

Equality refers to two objects being the same. Two objects being equal doesn't necessarily mean that they are the same object. In Java, we use the equals() method to check if two objects are equal. This is also called structural equality.

Equality can always be decided by looking at the object only. You don't need any external information to decide equality. Equality can change over time: I'm not equal to the person that I was 20 years ago.

Real-World Objects

When you are modeling real-world objects, you usually have some kind of ID to refer to it. For example, you might have a simple product definition with an ID and a price:

Java
 




x


 
1
public class Product {
2
  private final String id;
3
  private BigDecimal price;
4
  // rest of the code is omitted for brevity
5
}



Now, you need a way to check if two products are equal. So you go ahead and implement an equals method

Java
 




xxxxxxxxxx
1


 
1
public boolean equals(Object o) {  
2
  if (o == this) return true;
3
  if (o == null || this.getClass() != o.getClass()) 
4
    return false;
5
  Product that = (Product)o;
6
  return this.id.equals(that.id);
7
}



We used the ID field as most Java developers would, but is this right? Let's test it:
Java
 




xxxxxxxxxx
1


 
1
new Product("IBM", 142.05)  
2
  .equals(new Product("IBM", 110.03)) // true



I think we can agree that we could potentially lose a lot of money if we relied on this equals implementation to drive our trading decisions. So what happened here?

What we really wanted is to check if we are referring to the same product. But referential equality if not customizable in Java, it's always based on memory address and we cannot change that. If we could, we would make it use the ID field, but we cannot so we fall back to doing it in the equals, which is wrong.

The other thing we seem to have forgotten is that identity is external. It's not a property of the object itself. It's an external reference, so it should even be part of the object. How can we achieve that in Java? We can simply use a Map:

Java
 




xxxxxxxxxx
1


 
1
Map<String, Product&gt; products = ...
2
products.get("IBM") == products.get("IBM") // true
3
products.get("IBM") == products.get("459200101") // true




As you can see, we get what we expect. We can even use different IDs to refer to the same product if our Map has all the various product ID types. So, referential equality works as expected; now we can move on to fix our equals:

Java
 




xxxxxxxxxx
1
12


 
1
public class Product {
2
  // id is not part of the object any more
3
  private BigDecimal price;
4
  // equals is implemented in terms of all the fields
5
  public boolean equals(Object o) {
6
    if (o == this) return true;
7
    if (o == null || this.getClass() != o.getClass()) 
8
      return false;
9
    Product that = (Product)o;
10
    return this.price.compareTo(that.price) == 0;
11
  }
12
}




And this way, we get an equals() that doesn't directly lead to bankruptcy:

Java
 




xxxxxxxxxx
1


 
1
new Product(142.05).equals(new Product(110.03)) // false




Conclusion


  • Do not include ID fields in your Java domain classes.
  • Use all fields in your equals() and hashCode() implementation.

Further Reading

Object Identity and Equality in Java

Java (programming language) Object (computer science)

Published at DZone with permission of Attila Mihaly. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook