Is there a way to force type parameter in java generics to implement equals
method?
For example, I wrote this class: public class Bag<Item> implements Iterable<Item>
which has contains
method, that uses Item.equals
method. So I want to make sure that the passed Object in the generics will also implement the equals
method.
You could make an abstract base class called ItemBase
, make equals abstract and then have Item extend ItemBase
.
public abstract class ItemBase {
@Override
public abstract boolean equals(Object o);
}
public class Bag extends ItemBase
This would force anyone Implementing ItemBase to specifically implement equals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With