简体   繁体   中英

Generic interface with equals and hashCode methods, is it possible?

I'd like to define an interface that will be used to implement keys for a map. The map uses equals and hasCode to locate and compare keys. My keys need to override these with custom computations. Here is what I'd like to do. It's important that the complex key is used. Thanks

public interface CachedRequestKey<T>{
    public T complexKeyObject;

    @Override
    public boolean equals(T obj);

}

EDIT for down voters: I'm aware the above code is not valid. I'm looking for ideas to achieve an interface that insures the implementing class provides required methods using the generic type.

What you want isn't possible in Java. Object already implements equals and hashCode , so every subclass does automatically as well. There's no way for an interface or abstract class to require it to be reimplemented. It's assumed that equals and hashCode for a given class are implemented correctly for that class.

If you really need your classes to implement specific comparison operations and don't want to use the existing equality methods by accident, you could define your own comparison functions on you interface and require implementing classes to define those. Classes that already implement your equality mechanics in their equals and hashCode methods can delegate to the existing methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM