r/javahelp • • 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!

31 Upvotes

11 comments sorted by

18

u/Robyt3 Nov 07 '19

The equals- and hashCode-methods are used by the Collections Framework. For instance, when you add an item to a Set, the equals method will be used to determine if the item is already in the Set, so it isn't added again.

Comparator and Comparable deal with sorting / defining an order, whereas the equals-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- and hashCode-methods when you want multiple instances of your class to represent the same thing, if you use collections or call equals yourself.

3

u/AudioManiac Nov 07 '19

You need to override the equals- and hashCode-methods when you want multiple instances of your class to represent the same thing

Could you perhaps provide an example of this? What do you mean by the same thing? It's the only part I don't understand. Thank you

10

u/Robyt3 Nov 07 '19

Here is a small example if you want to store a Set of unique points:

public class Point {

    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // equals, hashCode implementations
}

Set<Point> points = new HashSet<>();
points.add(new Point(1, 2));
points.add(new Point(1, 3));
points.add(new Point(1, 2)); // should be equal to first point, but isn't same instance

// Prints 2 if equals and hashCode are implemented correctly
// Prints 3 if using reference equality
System.out.println(points.size());

1

u/RushTfe Nov 07 '19 edited Nov 08 '19

Imagine you have a class called "person" and a class called "player". Now imagine you're comparing a person against a player, and wants to know if they're the same (based on name, ID or whatever) then you can tell by equals method that a player is equal to another if they share those attributes.

@Override

public boolean equals(Object obj) {

boolean areEquals = false;

If (this.id == (Player) obj.getId())

    areEquals = true;

return areEquals;

}

This is example lacks more important stuff, like null handling or instances, but it's just an example

Edit to correct mistake pointed by u/indivisible

1

u/indivisible Nov 08 '19

Note though the the method being overridden is public boolean equals(Object o) from the base Java type Object. You can't Override using a Person argument as that method signature doesn't exist (unless it is in an intermediary parent class) though you can always implement it.

1

u/RushTfe Nov 08 '19

Yep, that's true forgot it. Different parameters means different methods. Gonna edit it for anyone who could read it later

4

u/desrtfx Out of Coffee error - System halted Nov 07 '19

First, and most commonly used: String comparison.

In Java, String is an object data type and if you want to check for content equality, you need to use .equals or .equalsIgnoreCase

2

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) and int hashCode().

1

u/morhp Professional Developer Nov 07 '19

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!

equals is always used when adding something to a Set or when using something as a key in a Map.

Let's assume you use a Map<RoadIdentifier, Double> to store the lengths of roads in a map. RoadIdentifier is a custom class that includes for example a city and a road name.

If you don't overide equals (and hashCode) for RoadIdentifier code like this will fail:

map.put(new RoadIdentifier("London", "Kings Road"), 1332.5);
// in another part of the code
Double length = map.get(new RoadIdentifier("London", "Kings Road"));
// length will be null if you don't override equals, as you used different instances

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's get() 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.