Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing type parameter to implement specific method in java generics

Tags:

java

generics

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.

like image 952
SharonKo Avatar asked Aug 19 '13 19:08

SharonKo


1 Answers

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

like image 167
Grammin Avatar answered Nov 15 '22 06:11

Grammin