简体   繁体   English

具有equals和hashCode方法的通用接口,可以吗?

[英]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. 该映射使用equals和hasCode来查找和比较键。 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. Java不可能实现您想要的。 Object already implements equals and hashCode , so every subclass does automatically as well. 对象已经实现了equalshashCode ,因此每个子类也会自动执行。 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. 假定为该类正确实现了给定类的equalshashCode

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. 已经在equals和hashCode方法中实现了相等机制的类可以委托给现有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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