How do I avoid this erasure error in Java?

89 Views Asked by At

I have a homemade storage object that is similar to Set interface methods. I want to make it compatible with Set so it can be compatible with Collections. The problem is that it is a generic class and that generic class uses the type variable as method parameters.

The two methods I am talking about:

I have:

remove(T var) {/*remove var*/}

Set interface has this:

remove(Object var) {/*remove var*/}

The compiler tells me that there is some kind of erasure error. I can change remove from remove(T var) what it is to removing(Object var) but I prefer not to do that.

Is there another way to do this that would make it compatible with Set without changing my original method signature?

1

There are 1 best solutions below

0
vbezhenar On

The reason why it's declared as (Object v) and not (T v) is because it removes all objects x where v.equals(x) == true. Please note that objects of different classes can be compared with each other and it's perfectly legal for them to be equal, because equals does not require objects to be of the same class.