More specifically I want an interface to compare objects which can be only compared for equality [e.g. complex numbers] but don\'t have total order on them. It should have [Not
In the end I opted to write what I do in similar cases. If I need special equality/hash - like for example keeping weak references. You can wrap the key like that. Overall it's not very different from the interface approach but it creates dumb instances (like HashMap/Hashtable for bucket entries). You might need extra unwrapping for keySet() and so on...
package t1;
public abstract class KeyX implements java.io.Serializable {
private static final long serialVersionUID = 0l;
final Key key;
final int hash;
protected KeyX(Key key){
this.key = key;
this.hash = hashCode(key);
}
protected abstract int hashCode(Key key);
//Key, Key will be way too strict and it'd required, key.getClass().isInstance(y) prior calling
protected abstract boolean equals(Key x, Object y);
@Override
public final boolean equals(Object obj) {
if (obj==this)
return true;
if (!(obj instanceof KeyX)){
return false;
}
final KeyX> other = (KeyX>) obj;
return this.key==other.key || (hash==other.hash && other.key!=null && equals(this.key, other.key));
}
@Override
public final int hashCode() {
return hash;
}
public final Key unwrap(){
return key;
}
}