1

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

4 Answers4

6

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.

Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
  • that helps a lot mate.. Also could you please explain what instanceOf does?? –  Nov 28 '11 at 07:42
  • `instanceof` will check to see if the `other` object is of type `T`. This prevents a possible exception when casting the object. If it is not of type `T`, the `equals` method should return false. – Beau Grantham Nov 28 '11 at 14:00
  • There is the error in the generic class when using the instanceof . The links describe the detail: http://stackoverflow.com/questions/5734720/java-generics-obj-instanceof-t . In short, the keyword "instanceof " is not allowed to use in the java generic class. – zhfkt Aug 11 '16 at 10:13
2

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;
    // ...
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Be careful of casting without checking to see if the object is as instance of T first. You may end up with a ClassCastException. – Beau Grantham Nov 24 '11 at 14:21
0

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;
}
0

you need this.

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

}
erimerturk
  • 4,230
  • 25
  • 25