Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
32 views11 pages

Redefining Java Object Equality

The document discusses the concept of object equality in Java, focusing on the importance of correctly implementing the equals method for custom classes. It highlights the differences between reference equality and content equality, providing examples and guidelines for overriding the equals method. Additionally, it suggests a utility method for fuzzy equality comparisons to enhance flexibility in equality checks.

Uploaded by

sayak.uc.barclay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views11 pages

Redefining Java Object Equality

The document discusses the concept of object equality in Java, focusing on the importance of correctly implementing the equals method for custom classes. It highlights the differences between reference equality and content equality, providing examples and guidelines for overriding the equals method. Additionally, it suggests a utility method for fuzzy equality comparisons to enhance flexibility in equality checks.

Uploaded by

sayak.uc.barclay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

(/) REFCARDS (/REFCARDZ)

TREND REPORTS (/TRENDREPORTS)


EVENTS (/EVENTS)  (/users/login.html) 
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance

(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)


The software you build is only as secure as the code
that powers it. Learn how malicious code creeps into
your software supply chain.

⌛ Save Your Seat

(https://web.cvent.com/hub/events/76ac3891-a39e-
45ef-b154-01cdf152ddce/landing?
utm_campaign=JFrog&utm_medium=Dzone%2520Web&utm_source=Announcements)

RELATED

Singleton: 6 Ways To Write and Use in Java Programming (/articles/singleton-six-ways-to-write-and-uses-in-Java)

Java vs. Scala: Comparative Analysis for Backend Development in Fintech (/articles/java-vs-scala-comparative-analysis-for-fintech)

How To Get Started With New Pattern Matching in Java 21 (/articles/how-to-get-started-with-new-pattern-matching-in-ja)

Creating a Deep vs. Shallow Copy of an Object in Java (/articles/creating-a-deep-vs-shallow-copy-of-an-object-in-ja)

Partner Resources
Events Trend Report Library
Discover upcoming and on-demand webinars, fireside chats, Our reports offer expert insights on adoption trends and
and virtual roundtables by industry leaders. Learn More ► emerging technologies on the horizon. Learn More ►

Presented by DZone Presented by DZone

×
(/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)  (/users/login.html)

Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance

(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)

×
DZone (https://dzone.com) (/)
REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) 
/ Coding (https://dzone.com/coding) / Java (https://dzone.com/java) / Redefining Java Object Equality
(/users/login.html)

Redefining Java Object Equality


Culture and Methodologies

(/culture-and-methodologies)
Data Engineering

(/data-engineering)
Software Design and Architecture

(/software-design-and-architecture)
Coding

(/coding)
Testing, Deployment, and Maintenance

(/testing-deployment-and-maintenance)

Object equality is often a hot topic for assessing concepts and one of the pillars of how many of the
implementations of Collection Frameworks work. Learn more.

By Soham Sengupta (/users/5062469/sohampayback.html) · Oct. 08, 24 · Tutorial

 Likes (4)  Comment (0)  Save  Tweet  Share  6.0K Views

Equality in Java
Object equality (https://dzone.com/articles/object-identity-and-equality-in-java) is often a hot topic for
assessing concepts and one of the pillars (the other is- hashCode() ) of how many of the
implementations of Collection Frameworks (https://dzone.com/articles/an-introduction-to-the-java-
collections-framework) work. We check equality by providing our own implementation for the method
public boolean java.lang.Object#equals(java.lang.Object other) . According to Oracle
documentation
(https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#equals(java.lang.Obj
ect)), the following mandates should be adhered to:

It is reflexive: For any non-null reference value x , x.equals(x) should return true .
It is symmetric: For any non-null reference values x and y , x.equals(y) should return true if
and only if y.equals(x) returns true .
It is transitive: For any non-null reference values x , y , and z , if x.equals(y) returns true and
× y.equals(z) returns true , then x.equals(z) should return true .
It is consistent(/) : For any non-null reference values x and y , multiple invocations of x.equals(y)
REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)
consistently return true or consistently return false , provided no information used in equals

(/users/login.html)

comparisons
Culture and Methodologieson the Data
objects are modified.
Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance

(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)


For any non-null reference value x , x.equals(null) should return false .

Please note that there exist a few more related to using it along with hashCode() , but we do not
discuss them here for brevity, assuming the readers are already aware of them.

Reference Equality or Content Equality?


The term "equality" can itself be ambiguous, since we can either talk about reference equality or be
interested in content equality. Let us illustrate both with a simple example. However, the reader may
choose to skip this section and jump into the main topic of discussion at one's own discretion.

Assume a class (POJO), LaptopCharger :


Java
1 package com.yourcompany.model;
2
3 /**
4 * An AC-to-DC converter LaptopCharger
5 *
6 */
7 public class LaptopCharger {
8 private String manufacturer;
9 private int wattage; // Consumption: Volt times Amp.
10 private float outputCurrent; // output Amp.
11 private float outputVoltage; // output Volt
12 private double price;
13 private String connectorJackType; // E.g. USB-C, pin etc.
14
15 // Setters and Getters follow here
16
×
17 }
18
(/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)  (/users/login.html)

Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
Note that we did not override
(/culture-and-methodologies)
any method
(/data-engineering)
of java.lang.Object (which,
(/software-design-and-architecture) (/coding)
is inherited by any Java class
(/testing-deployment-and-maintenance)
(https://dzone.com/articles/understanding-classes-in-java-part-1)); the default implementations,
therefore, apply here.

The below code snippet outputs false false :


Java
1 LaptopCharger charger_A = new LaptopCharger(65, 3.25f, 19.0f, 100, "usb-c");
2 LaptopCharger charger_B =new LaptopCharger(65, 3.25f, 19.0f, 100, "usb-c");
3 boolean refEqulas=charger_A==charger_B;
4 boolean equals=charger_A.equals(charger_B);
5 System.out.println(refEqulas+" "+equals);

We see that reference equality is the default return value of the equals method. However, consider
that Bob was searching a popular e-commerce site for a charger for his laptop. His laptop requires a 65-
watt/19.8Volt type-C charger, but he finds that the one given by his laptop manufacturer is not going to
reach him anytime soon. He, therefore, searches for a close alternative. The meaning of equality, in this
case, is content equality as shown below:
Java
1 @Override
2 public boolean equals(Object obj) {
3 if (null == obj)
4 return false;
5 if (obj == this)
6 return true;
7 if (!(obj instanceof LaptopCharger))
8 return false;
9 LaptopCharger other = (LaptopCharger) obj;
×
10
11
12
13 }
return this.wattage == other.wattage && this.outputCurrent == other.outputCurrent
&&(/)this.connectorJackType.equals(this.connectorJackType);
REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)  (/users/login.html)

Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance

(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)

The output is: false true .

However, the equals method can be overridden if these conditions are met:

1. The code, i.e. LaptopCharger is open to us.


2. This logic is accepted across the business domain.

Otherwise, we can use Objects.compare(..)


(https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#compare(T,T,java.uti
l.Comparator)) somewhat like the following:
(Important note: Unless we are certain about ordering the objects, it may be against the prescribed
contract to use Comprator<T> for just checking content equality.)
Java
1 Comparator<LaptopCharger> specificationComparator=(x,y)->{
2 if(x.wattage == y.wattage && x.outputCurrent == y.outputCurrent
3 && x.connectorJackType.equals(y.connectorJackType)) return 0;
4 else return 1;
5 };
6
7
8 int t=Objects.compare(charger_A, charger_B, specificationComparator);
9
10
11 System.out.println(t);

×
How Much Equal Is an Object to Another?: Degree of Equality
How Much Equal Is an Object to Another?: Degree of Equality
(/)
So far, we talked aboutREFCARDS (/REFCARDZ)
content equality TREND REPORTS (/TRENDREPORTS)
and it was all EVENTS (/EVENTS)
in black and white. However, what  if we needed
(/users/login.html)

toCulture
check and the degree of equality
Methodologies beyond just
Data Engineering falseDesign
Software andandtrue ? To elaborate
Architecture Codingon this Testing,
point, let us assume
Deployment, the
and Maintenance

following fields:
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)

1. Equality of wattage , outputCurrent , and outputVoltage


2. Equality of charger connectivity : connectorJackType
3. Brand: manufacturer
4. Price of the item

Hypothetical business requirements are:

If all 4 points above are the same, we consider 100% equality.


[2] must be the same.
A small variation in output current and voltage may be permissible. (Alert: in real life, this may
not be the best practice!)
The manufacturer of the charger is not required to be the same as the laptop's but is recommended
to be.
Price: Customers always hunt for low prices, discounts, and of course, value for money! A small
compromise for a few other constraints is granted.

Restricting the discussion to Java SE 17 (https://dzone.com/articles/title-exploring-exciting-new-features-


in-java-17-w), we can address this scenario using third-party libraries like Fuzzy-Matcher
(https://github.com/intuit/fuzzy-matcher), etc.

However, would this not just be great if Java itself handled this by using a utility method in
×
java.util.Objects (https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html)?
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)
small and coarse prototype to illustrate what would have been good to have: 
Note that it does not until this version. I just wish it were a part of Java SE and here itself! Below is a
(/) REFCARDS (/REFCARDZ) (/users/login.html)

Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
Java
(/culture-and-methodologies)
(/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
1 /**
2 * @param t1
3 * @param t2
4 * @param fuzzyComparator
5 * @return R the result. No type is enforced to provide more flexibility
6 */
7 public static <T, R> R fuzzyEquals(T t1, T t2, BiFunction<? super T, ? super T, R> fuzzyComparator) {
8 return fuzzyComparator.apply(t1, t2);
9 }

The first two parameters are of type T and last one, the comparator itself is a BiFunction<? super T,
? super T, R> .

In this example, I did not enforce a return type for the method, leveraging the power of generics and
functional programming to provide more flexibility. This eliminates the need for a strict return type
such as double as well as a dedicated functional interface like FuzzyComprator which would otherwise
have looked somewhat like this:
Java
1 @FunctionalInterface
2 public interface Comparator<T>{
3 // other stuff like static, default methods etc.
4
5 double compare(T o1, T o2)
6
7 }

×
Below is a simple illustration using it:
Java (/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS)
1 BiFunction<LaptopCharger, LaptopCharger, OptionalDouble> mySimpleFuzzyCompartor = (x, y) -> {
 (/users/login.html)

2
Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
3 if (x.connectorJackType.equals(y.connectorJackType))
(/culture-and-methodologies) (/data-engineering) {
(/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
4 if (x.wattage == y.wattage && x.outputCurrent == y.outputCurrent
5 && x.manufacturer.equals(y.manufacturer) && x.price == y.price)
6 return OptionalDouble.of(1.0D); // Full match
7
8 if (x.wattage == y.wattage && x.outputCurrent == y.outputCurrent
9 && x.manufacturer.equals(y.manufacturer))
10 return OptionalDouble.of(1.0 - (x.price - y.price) / x.price);// Price based match
11
12 if (x.wattage == y.wattage && x.outputCurrent == y.outputCurrent)
13 return OptionalDouble.of(1.0 - 0.2 - (x.price - y.price) / x.price); //
14 if (x.wattage == y.wattage && Math.abs(x.outputCurrent - y.outputCurrent) < 0.15)
15 return OptionalDouble
16 .of(1.0 - 0.2 - Math.abs((x.outputCurrent - y.outputCurrent) / x.outputCurrent));
17 return OptionalDouble.empty();
18 } else {
19 return OptionalDouble.empty();
20 }
21 };
22
23
24
25
26 OptionalDouble fuzzyEquals = fuzzyEquals(charger_A, charger_B, mySimpleFuzzyCompartor);
27
28
29 System.out.println(fuzzyEquals);
30

We used OptionalDouble as the return type of the fuzzyEquals .

Readers are strongly encouraged to introduce the method, fuzzyEquals , in java.util.Objects and
×
use it and get it benchmarked Once we have that satisfactory Collection Frameworks might be made to

use it and get it benchmarked. Once we have that satisfactory, Collection Frameworks might be made to
undergo relevant contract upgradation
(/) REFCARDS TRENDto
(/REFCARDZ) strongly
REPORTS support beyond-the-Boolean comparison!
(/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)

Culture and Methodologies Data Engineering Software Design and Architecture Coding Testing, Deployment, and Maintenance
Functional Programming Java (Programming Language) Object (Computer Science) Data Types
(/culture-and-methodologies) (/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)

Opinions expressed by DZone contributors are their own.

RELATED
Singleton: 6 Ways To Write and Use in Java Programming

Java vs. Scala: Comparative Analysis for Backend Development in Fintech

How To Get Started With New Pattern Matching in Java 21

Creating a Deep vs. Shallow Copy of an Object in Java

Video Library
Access On-Demand Webinars, Fireside Chats, and
Roundtables in our video library. Click Here ►

Presented by DZone

ABOUT US
About DZone (/pages/about)
ADVERTISE
Advertise with DZone Let's be friends:    
Support and feedback (https://advertise.dzone.com)
(/pages/feeds)
(https://twitter.com/DZoneInc)
(https://www.facebook.com
(https://www.linkedin.c
(mailto:[email protected])
Community research
(/pages/dzone-community-

× research)
Sitemap (/sitemap)
(/)
CONTRIBUTE ON DZONE
REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
CONTACT US
EVENTS (/EVENTS)  (/users/login.html)

Article Submission Guidelines


Culture and Methodologies 3343 Perimeter
Data Engineering Hill Drive
Software Design and Architecture Coding Testing, Deployment, and Maintenance
(/articles/dzones-article-
(/culture-and-methodologies) Suite 100
(/data-engineering) (/software-design-and-architecture) (/coding) (/testing-deployment-and-maintenance)
submission-guidelines) Nashville, TN 37211
Become a Contributor [email protected]
(/pages/contribute) (mailto:[email protected])
Core Program (/pages/core)
Visit the Writers' Zone (/writers-
zone)

LEGAL
Terms of Service
(https://technologyadvice.com/terms-
conditions/)
Privacy Policy
(https://technologyadvice.com/privacy-
policy/)

You might also like