A forced type parameter for implementing a particular method in java generics

Is there a way to force a type parameter in java generics to implement the equals method? For example, I wrote this class: public class Bag<Item> implements Iterable<Item> , which has a contains method that uses the Item.equals method. Therefore, I want to make sure that the passed object in generics will also implement the equals method.

+6
source share
1 answer

You can create an abstract base class called ItemBase , make it equal to abstract, and then Item extend ItemBase .

 public abstract class ItemBase { @Override public abstract boolean equals(Object o); } public class Bag extends ItemBase 

This would force anyone to implement ItemBase to specifically implement equals

+8
source

Source: https://habr.com/ru/post/952061/


All Articles