Java无法自动推断通用参数

时间:2019-10-26 14:54:49

标签: java generics diamond-operator

我已定义此方法:

public static <E extends Comparable<E>> NavigableSet<E> navigableSet (List<E> l)

我写的时候:

NavigableSet<Integer> set = Sets.navigableSet(new ArrayList<Integer>());

一切都很好,但是如果我改写这个:

NavigableSet<Integer> set = Sets.navigableSet(new ArrayList<>());

Java无法自动推断Integer类型。我收到以下错误:

error: no suitable method found for navigableSet(ArrayList<Object>)
NavigableSet<Integer> set = Sets.navigableSet(new ArrayList<>());
                                ^
method Sets.<E#1>navigableSet(List<E#1>) is not applicable
  (inferred type does not conform to equality constraint(s)
    inferred: E#2
    equality constraints(s): E#3)

为什么?是什么导致Java无法做出正确的推断?

我的Java版本是:

openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.5+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.5+10, mixed mode)

0 个答案:

没有答案