Redefining Java Object Equality
Redefining Java Object Equality
(https://web.cvent.com/hub/events/76ac3891-a39e-
45ef-b154-01cdf152ddce/landing?
utm_campaign=JFrog&utm_medium=Dzone%2520Web&utm_source=Announcements)
RELATED
Java vs. Scala: Comparative Analysis for Backend Development in Fintech (/articles/java-vs-scala-comparative-analysis-for-fintech)
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 ►
×
(/) REFCARDS (/REFCARDZ)
TREND REPORTS (/TRENDREPORTS)
EVENTS (/EVENTS) (/users/login.html)
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)
(/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.
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
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.
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.
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
However, the equals method can be overridden if these conditions are met:
×
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)
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
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)
RELATED
Singleton: 6 Ways To Write and Use in Java Programming
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)
LEGAL
Terms of Service
(https://technologyadvice.com/terms-
conditions/)
Privacy Policy
(https://technologyadvice.com/privacy-
policy/)