Home > Blockchain >  Java: cannot use '<>' with anonymous inner classes, cannot run in IDE but can compil
Java: cannot use '<>' with anonymous inner classes, cannot run in IDE but can compil

Time:09-26

When I wrote the following code in my IDE (eclipse and intellij), it will show red wave line below the Comparator<> and I have to write Comparator<Integer>() instead of Comparator<>()

import java.util.*;

class Solution {
    public static void main(String[] args) {
        Comparator<Integer> comp = new Comparator<>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };
        System.out.println(comp);
    }
}

If I run my code in IDE, it will show the error java: cannot infer type arguments for java.util.Comparator<T> reason: cannot use '<>' with anonymous inner classes.

However, if in terminal javac Solution.java and java Solution, the code works.

My Question:

  1. Why cannot I ingore the type and use diamond operator for anonymous class in IDE?

  2. Why does IDE show different behaviors from terminal?

CodePudding user response:

So to answer your questions:

  1. Duplicate of Why can't diamond infer types on anonymous inner classes?
  2. You most likely use another java version in your terminal than in your IDE. The code doesnt compile on jdk 7/8, but does on jdk 9

The reason why it works on jdk9 is the following enhancement by project coin: https://bugs.openjdk.java.net/browse/JDK-8062373

  • Related