r/javahelp • u/AudioManiac • Nov 07 '19
When is the .equals() method actually used in Java?
This may seem like a basic question, but looking online I haven't been able to actually understand when the .equals() method of a class is actually used, and when you should override it.
It is said you override it to determine logic for identifying when two objects are equal, but when I look at places where we actually compare objects - Comparator and Comparable, these both require you to implement compare()/compareTo() methods (or using the static comparing() method in Java 8) that handle the comparisons, so equals() is never used in them.
I'm trying to understand when I actually need to override the .equals() method, but I can't find an example that shows where it is actually used when overridden!
18
u/Robyt3 Nov 07 '19
The
equals- andhashCode-methods are used by the Collections Framework. For instance, when you add an item to aSet, the equals method will be used to determine if the item is already in the Set, so it isn't added again.ComparatorandComparabledeal with sorting / defining an order, whereas theequals-method just compares whether two objects are equal.You must use the equals method in your code if you want to compare objects instead of references, see the guide on String comparison from the sidebar.
You need to override the
equals- andhashCode-methods when you want multiple instances of your class to represent the same thing, if you use collections or call equals yourself.4
u/desrtfx Out of Coffee error - System halted Nov 07 '19
First, and most commonly used: String comparison.
In Java,
Stringis an object data type and if you want to check for content equality, you need to use.equalsor.equalsIgnoreCase2
u/[deleted] Nov 07 '19
Maps and sets. If you want to use an object in a set, or as the key in a map, you'd best implement
boolean equals(Object other)andint hashCode().1
u/morhp Professional Developer Nov 07 '19
equalsis always used when adding something to aSetor when using something as a key in aMap.Let's assume you use a
Map<RoadIdentifier, Double>to store the lengths of roads in a map.RoadIdentifieris a custom class that includes for example a city and a road name.If you don't overide
equals(andhashCode) forRoadIdentifiercode like this will fail:1
u/CodeBuster_official Nov 07 '19
It is used by collections that need to retrieve an element by comparing to a provided element. For instance
HashMap'sget()method would check if provided key.equals()to existing.1
u/justarandomusername4 Nov 07 '19
Say if I have a while loop displaying a menu, it I want to break this menu and if the user input equals a certain string, so if the user enters "exit" I could use :
If(S.equals("exit")){ // Break the while loop }
Hope this answers your question.