java - Is there any Comparable not comparable to itself? -
in contract of comparable, there's nothing forcing object comparable itself. it's just
strongly recommended, not strictly required (x.compareto(y)==0) == (x.equals(y))
which implies it's recommended x.compareto(x)
not throw. it's possible write a
class x implements comparable<y> { ... }
where x
, y
2 unrelated classes. can't see for, in java 8 version of hashmap
there's corresponding check.
- is allowed implement
x implements comparable<y>
2 unrelated classes? - does make sense?
i guess answers yes , no, it's guess
comparable
promotes contract comparisons should consistent equals, i.e. (a.compareto(b) == 0) == a.equals(b)
. not force , weird contract can enforced.
so create a:
class dumbinteger implements comparable<dumbinteger> { private final int i; public dumbinteger(int i) { this.i = i; } public int compareto(dumbinteger di) { return 0; } public boolean equals(object other) { /* checks */ return other.i == this.i; } }
and create a:
class dumberinteger implements comparable<string> { private final int i; public dumberinteger(int i) { this.i = i; } public int compareto(string s) { return 0; } public boolean equals(object other) { /* checks */ return other.i == this.i; } public static void main(string[] args) { system.out.println(new dumberinteger(0).compareto("abc")); } }
but there no point in doing that. in case not specific java 8 comparable interface has been there since java 2 , "generified" in java 5.
but not flaw in comparable interface per se, because i don't think there way in java create generic interface i<t>
can implemented classes subtypes of t
.
Comments
Post a Comment