简体   繁体   English

Java 7 -> 无法使用比较器推断类型

[英]Java 7 -> Cannot infer Type with Comparator

When I use java 7 to compile a code using PriorityQueue with Comparator, compiler sends error:当我使用 java 7 使用 PriorityQueue 和 Comparator 编译代码时,编译器发送错误:

 cannot infer type arguments for Comparator<T>;
    Comparator<Map.Entry<Double, PureColor>> colorComparator  = new Comparator<>() {
                                                                              ^
  reason: cannot use '<>' with anonymous inner classes

Why this, and how can I compile me code:为什么这样,以及如何编译我的代码:

    Comparator<Map.Entry<Double, PureColor>> colorComparator  = new Comparator<Map.Entry<Double, PureColor>>() {

      @Override
      public int compare(Map.Entry<Double, PureColor> o1, Map.Entry<Double, PureColor> o2) {
        return o1.getKey().intValue() - o2.getKey().intValue();
      }
    };

    PriorityQueue<Map.Entry<Double, PureColor>> minHeap = new PriorityQueue<>(colorComparator);

It is a limitation in java-7 the <> operator is not supported for anonymous classes这是 java-7 中的一个限制,匿名类不支持<>运算符

Class Instance Creation Expressions Class 实例创建表达式

It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.如果 class 实例创建表达式使用类的类型 arguments 的“<>”形式声明匿名 class,则这是一个编译时错误。

But from jdk-9 <> operators is supported for anonymous classes但是从 jdk-9 开始,匿名类支持<>运算符

What's New for the Java Language in JDK 9 JDK 9 中 Java 语言的新增功能

Allow the diamond with anonymous classes if the argument type of the inferred type is denotable.如果推断类型的参数类型是可表示的,则允许使用匿名类的菱形。

So to resolve this issue either upgrade java 7 to java 9 or just define the generic parameters like second approach in your example因此,要解决此问题,请将 java 7 升级到 java 9 或仅定义通用参数,如示例中的第二种方法

Comparator<Map.Entry<Double, PureColor>> colorComparator  = new Comparator<Map.Entry<Double, PureColor>>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM