从Java中的泛型类型推断泛型类型(编译时错误)

mad*_*n54 6 java generics types

我有一个静态函数,其泛型类型具有以下签名 T

public static<T> List<T> sortMap(Map<T, Comparable> map)
Run Code Online (Sandbox Code Playgroud)

应返回带有某些属性的地图键列表.

现在我想传递一个类型的泛型HashMap S

Map<S,Double> map
Run Code Online (Sandbox Code Playgroud)

调用泛型类中的静态函数,该类将映射作为成员变量.

我在下面列出了一个最小的代码示例.

但是,我得到一条错误消息(S并且T都是T,但在我的代码的不同范围内,即T#1= T,T#2= S):

  required: Map<T#1,Comparable>
  found: Map<T#2,Double>
  reason: cannot infer type-variable(s) T#1
  (argument mismatch; Map<T#2,Double> cannot be converted to Map<T#1,Comparable>)
Run Code Online (Sandbox Code Playgroud)

怎么解决这个问题?我很惊讶Java不允许从泛型类型推断泛型类型.Java中的哪种结构可以用来处理那种更抽象的代码推理?

代码:

public class ExampleClass<T> {
    Map<T, Double> map;
    public ExampleClass () {
        this.map = new HashMap();
    }
    //the following line produces the mentioned error
    List<T> sortedMapKeys = UtilityMethods.sortMap(map);
}

public class UtilityMethods {
     public static<T> List<T> sortMap(Map<T, Comparable> map) {
        // sort the map in some way and return the list
     }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 8

这不是与问题TS,但与ComparableDouble.

错误的原因是a Map<T, Double>不是aMap<T, Comparable>.

你必须扩大第二个类型参数的范围.就像是:

public static <T, S extends Comparable<S>> List<T> function(Map<T, S> map) {
    //implementation
}
Run Code Online (Sandbox Code Playgroud)

然后,您将能够使用以下方法调用该方法:

Map<S, Double> map = new HashMap<S, Double>();
function(map);
Run Code Online (Sandbox Code Playgroud)