The Java documentation for Comparable recommends that compareTo be consistent with equals (because of the behavior in sorted sets or sorted maps).
I have a Player object which is mutable. Player will not be used in any kind of sorted set or sorted map.
I want to have an array of Players (Player[]) and assign each player a random order of play (a member variable m_nPlayOrder), then sort them in that array based on their m_nPlayOrder member variable.
I will implement the Comparable interface and the compareTo function to achieve this.
My question is, is it ok in this case if Player has a compareTo that is NOT consistant with equals? It will not be consistant with equals unless I also override equals (and hashCode) and have it return true if the Players m_nPlayerOrder are equal. I do not want to do that.
UPDATE:
Thanks everyone for the replys! I’m going with implementing the Comparator instead of Comparable.
You could implement a
java.util.Comparator(a stand-alone object that “knows” yourPlayerclass and compares accordingly) and use that instead of implementingComparablein the class.Comparatorhas the advantage in that you can implement any number of them for different types of sorts, rather than the singleComparable.