Tal
Tal

Reputation: 11

Call the overload method 'equals' for a generic type

I'm trying to call the 'equals' method from a generic type. On run time the type has an overload for 'equals' but the Object.equals(Object obj)‬ is still triggered.

This is the generic class which calls 'equals'.

public class SortedGroup <T> {
    void func(T element1,T element2) {
        if (element1.equals(element2))
            System.out.println("yes");
        else
            System.out.println("no");
}

This is the new type class that overloads 'equals'

public class Person {
    private int ID;
    public Person(int ID) {
        this.ID = ID;
    }
...
    public boolean equals(Person o) {
        return (this.ID == o.ID);
    }
...
}

and this is main.


Person p1 = new Person(1);
Person p2 = new Person(1);
SortedGroup<Person> SG = new SortedGroup<Person>();

SG.func(p1,p2);
}

I expect the output be yes but the actual output no

Upvotes: 0

Views: 359

Answers (1)

rgettman
rgettman

Reputation: 178253

You are not overriding equals, you are overloading it (same method name, different signature). To override equals from Object correctly, you must match the method signature. This means that your equals method must take an Object, not a Person.

public boolean equals(Object o) {  // ...

It is good practice to include the @Override annotation on any method intended to override a method from a superclass or implement a method from an interface. If you had done so, then the compiler would have alerted you to the fact that your method didn't override equals.

@Override
public boolean equals(Object o) {  // ...

This also means that you'll need to test if the object passed in is actually a Person before casting and comparing member values.

It is also good practice to override hashCode so that is is consistent with equals, according to the hashCode contract.

Upvotes: 4

Related Questions