user702026
user702026

Reputation:

equals method in java generic class

I hava a generic class called ArrayBag. I want to override equals method. So i wrote

public boolean equals(T other){

} // gives error

error message: Name clash: The method equals(T) of type ArrayBag has the same erasure as equals(Object) of type Object but does not override it

Upvotes: 1

Views: 6983

Answers (4)

IstariKnight
IstariKnight

Reputation: 1

Any time you need to override a method, the signature must be the same as the method to be overriden. Therefore you must pass Object as the one and only argument to your equals method for it to function as desired.

As an alternative to Grantham's solid solution, you can use getClass() in place of instanceof, if for example you plan on extending your generic class and don't want sub class instances to ever equal your super class instances.

That would look like:

@Override
public boolean equals(Object other) {
    if (other != null && getClass() == other.getClass()) {
        T o = (T) other;

        // ...

    }
    return false;
}

Upvotes: 0

Beau Grantham
Beau Grantham

Reputation: 3456

The equals method you are trying to override expects an Object. When your code is translated to byte code, type erasure transforms your T into an Object, which conflicts with the existing equals method.

@Override
public boolean equals(Object other) {
    if (other instanceof T)
    {
        T o = (T) other;
        ...
    }
}

Inside the method you can handle casting to T.

Upvotes: 6

erimerturk
erimerturk

Reputation: 4288

you need this.

public boolean equals(Object other){
      T t = (T) other;

}

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117589

Replace equals(T other) with equals(Object other), and then cast other to T inside the method implementation.

public boolean equals(Object other)
{
    T t = (T) other;
    // ...
}

Upvotes: 2

Related Questions