0

I'm using a TreeMap (SortedMap) whose keys are Object[] with elements of varying types.

TreeMap's equals() doesn't work on Object[] like Arrays's equals() would do -- which means it won't work when using its methods like containsKey() and get() unless I workaround it.

Is there somewhere a solution for this that doesn't involve creating a whole new Class?

EDIT :

Just to make it clear, I made a mistaken assumption. Creating a new Comparator(){} also does affect every method that uses equality, such as equals(), not only the tree sorter.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
  • See also http://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java – Raedwald Aug 11 '14 at 06:35
  • possible duplicate of [Does it make sense for equals and compareTo to be inconsistent?](http://stackoverflow.com/questions/794961/does-it-make-sense-for-equals-and-compareto-to-be-inconsistent) – Raedwald Aug 11 '14 at 06:38

2 Answers2

8

Is there somewhere a solution for this that doesn't involve creating a whole new Class?

No. In fact, you shouldn't be using mutable values for map keys at all.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    @Trevor The problem is that an array could be changed after insterting it into the tree. At that point, it could be in the wrong place in the tree. Therefore, it is unsafe to use arrays as keys. – 101100 Mar 19 '12 at 13:50
1

While I agree with Matt Ball that you generally shouldn't use mutable (changeable) types as your keys, it is possible to use a TreeMap in this manner as long as you are not planning on modifying the arrays once they are in the tree.

This solution does involve the creation of a class, but not a new Map class, which is what it seems you are asking. Instead, you would need to create your own class which implements Comparator<Object[]> that can compare arrays. The class could use the Arrays.equals() method to determine if they are equal, but would need to also have a consistent rule to determine which array comes before another array when the arrays are not equal.

Community
  • 1
  • 1
101100
  • 2,666
  • 23
  • 28
  • 1
    You don't need to override `equals` or `hashCode` with a `TreeMap`. From the [documentation for TreeMap](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html): "a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal." All you need to implement is the `Comparator` as you mentioned and the tree map will work. (Again, assuming you never change the arrays after inserting them.) – 101100 Mar 19 '12 at 15:22