-1

I'm working on an enterprise application. It was working fine earlier when the system had JDK1.6.+. I upgraded my JDK to 1.7.+. After that, I'm getting the error:

Caused by: java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)

Although I have solved my problem by switching between the JDK versions. I want to understand why the error is coming after upgrading to JDK 7. Obviously, there would be some changes in the implementation.But I want to understand that. I tried to check the Documentation of keystroke class. But I got nothing related to this.

Can someone explain this? Thanks in advance.

user207421
  • 305,947
  • 44
  • 307
  • 483
Raj Wadhwa
  • 335
  • 2
  • 13
  • 1
    @Jarrod: This question doesn't have any answer. I asked the reason for why it's working when app is running with JDK 1.6 and not with JDK 1.7 – Raj Wadhwa Apr 22 '15 at 09:58

2 Answers2

0

A TreeMap requires the key class to be orderable because it creates a tree of keys that are ordered. So you need to provide a way of ordering the keys, either via natural ordering (i.e., implementing the Comparable interface in the key class) or via a comparator class provided at TreeMap construction time.

KeyStroke does not implement Comparable and therefore does not provide natural ordering. This is the reason for the error. Simply provide a Comparator implementation that takes care of providing a way of ordering the keys, for example (ordering by keycode):

map = new TreeMap<KeyStroke, YourValueClass>(new Comparator<KeyStroke>() {
  public int compare(KeyStroke o1, KeyStroke o2) {
    return o1.getKeyCode() - o2.getKeyCode();
  }
});

More info about ordering requirements of TreeMap: How can I sort the keys of a Map in Java?

How Red-Black Trees (what TreeMap is) work, this should clarify why the key needs to be orderable (because it must be determined where to put it in the tree of keys): Explanation of Red-Black tree based implementation of TreeMap in JAVA

Community
  • 1
  • 1
EmirCalabuch
  • 4,756
  • 1
  • 25
  • 20
0

Why a TreeMap requires a class to be Comparable is nicely explained by other answers.

The other answers do not explain why you have the problem after changing from Java 6+ to Java 7+. The behavior of TreeMap is the same for Java 6 and 7 (I checked it in my IDE). Maybe your code uses another implementation in Java 7 due to Depency Injection. Just a guess. Could you check how your map is instantiated?

Community
  • 1
  • 1
remipod
  • 11,269
  • 1
  • 22
  • 25