1

I have below code which compiles perfectly fine with maven but Intellij keeps on giving me error saying Inconvertible types can not cast 'K' to java.lang.Long.

public class BPlusTree<K extends Comparable<K>, T> {

    public void debug(K time) {
      Long l = (Long) time;
    }
}

When I remove the extends Comparable<K> part from the class definition, intellij stops giving this error. What is happening here? I know this casting can throw a runtime ClassCastException but why the compilation error?

Nullpointer
  • 1,086
  • 7
  • 20

1 Answers1

1

Comparable is a bit weird when dealing with generics. I believe the correct definition is below:

class BPlusTree<K extends Comparable<? super K>, T> {

    public void debug(K time) {
      Long l = (Long) time;
    }

}

There's a good explanation of why it needs to be this way here: Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code?

markspace
  • 10,621
  • 3
  • 25
  • 39