Consider a class with a comparable (consistent with equals) and a non-comparable field (of a class about which I do not know whether it overrides Object#equals
or not).
The class' instances shall be compared, where the resulting order shall be consistent with equals, i.e. 0
returned iff both fields are equal (as per Object#equals
) and consistent with the order of the comparable field. I used System.identityHashCode
to cover most of the cases not covered by these requirements (the order of instances with same comparable, but different other value is arbitrary), but am not sure whether this is the best approach.
public class MyClass implements Comparable<MyClass> {
private Integer intField;
private Object nonCompField;
public int compareTo(MyClass other) {
int intFieldComp = this.intField.compareTo(other.intField);
if (intFieldComp != 0)
return intFieldComp;
if (this.nonCompField.equals(other.nonCompField))
return 0;
// ...and now? My current approach:
if (Systems.identityHashCode(this.nonCompField) < Systems.identityHashCode(other.nonCompField))
return -1;
else
return 1;
}
}
Two problems I see here:
- If
Systems.identityHashCode
is the same for two objects, each is greater than the other. (Can this happen at all?) - The order of instances with same
intField
value and differentnonCompField
values need not be consistent between runs of the program, as far as I understand whatSystems.identityHashCode
does.
Is that correct? Are there more problems? Most importantly, is there a way around this?