代码之家  ›  专栏  ›  技术社区  ›  Nullpointer

Java泛型-不能将K强制转换为Long

  •  1
  • Nullpointer  · 技术社区  · 9 年前

    我有以下代码,可以用maven编译得很好,但Intellij不断给我错误提示 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;
        }
    }
    

    当我移除 extends Comparable<K> ClassCastException 但是为什么会出现编译错误呢?

    1 回复  |  直到 9 年前
        1
  •  1
  •   markspace    9 年前

    Comparable 在处理泛型时有点奇怪。我认为正确的定义如下:

    class BPlusTree<K extends Comparable<? super K>, T> {
    
        public void debug(K time) {
          Long l = (Long) time;
        }
    
    }
    

    这里有一个很好的解释为什么需要这样做: Explanation of generic <T extends Comparable<? super T>> in collection.sort/ comparable code?