Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid warning when implementing equals on class with generics

I have the following code:

public abstract class A<T extends B<? extends A<T>>>{

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        A other = (A) obj; // warning here: "A is a raw type"
        // [...]
    }
}

How to avoid both "A is a raw type" and "Type safety: unchecked cast" at the specified line? Is there a hack of some sort or I am doing something wrong with my classes?

Thanks

like image 629
Jean Logeart Avatar asked Sep 19 '26 11:09

Jean Logeart


1 Answers

If the parameterized type of the compared A doesn't matter, declare and cast it as A<?>:

A<?> other = (A<?>) obj;

This will remove the warning.

like image 160
Paul Bellora Avatar answered Sep 21 '26 00:09

Paul Bellora