Task 3 of 5 · 0 solved · 5 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.3 Object and equals — writing it correctly

Lesson

Три части правильного equals

Overriding equals has a catch: the inherited signature takes an Object, not your class. Anything at all can be passed in, so the method must defend itself.


Образец

@Override
public boolean equals(Object other) {
    if (!(other instanceof Point)) {   // 1. is it even a Point?
        return false;
    }
    Point p = (Point) other;           // 2. now it is safe to convert
    return x == p.x && y == p.y;       // 3. compare the contents
}

Miss the first step and passing a String crashes the program. Write public boolean equals(Point other) instead, and you have not overridden anything — you have added a second, unrelated method, and the library will keep calling the old one.

Once equals is right, list.contains(...) and list.indexOf(...) start working with your objects, because they use equals internally.


▶ Try it: run this, then change something and run it again.



The parameter of an overriding equals must be of type...


What happens if you skip the instanceof check?


Type exactly what this program prints.

class Tag {
    private String text;

    public Tag(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Tag)) {
            return false;
        }
        Tag t = (Tag) other;
        return text.equals(t.text);
    }
}

public class Main { public static void main(String[] a){
    Tag x = new Tag("hi");
    Tag y = new Tag("hi");
    System.out.println(x.equals(y));
    System.out.println(x.equals(42));
}}

Writing public boolean equals(Point other) instead...


True or false?