Question

public class StrangeParamMethod {

    static void f(ArrayList<String> list){};

    public static void main(String... args){
        ArrayList<String> list = new ArrayListGenerator().list(); //assigns without problems
        f(new ArrayListGenerator().list());  //compile error
    }
}

class ArrayListGenerator   {
    <K> ArrayList<K> list(){
        return new ArrayList<K>();
    }
}

Please tell, why do I get compile error at the pointed string, when at the string over no problem occurs. I know how solve that compile error, but I want to know why there is such difference in this particular case.

P.S. I know that compile error solves by f(new ArrayListGenerator().<String>list());

Was it helpful?

Solution

Because the compiler team at Oracle didn't bother implementing type inference for the second situation, but did it for the first situation (where the type can be inferred from the variable the expression is assigned to).

Java 8 comes with large improvements in terms of type inference, so I wouldn't be surprised if it compiled with the Java 8 compiler.

OTHER TIPS

When calling a generic method without a type paramater, it will use a raw type (no type inference). Type inference works when a type is given in the line of code (first case).

Of course, putting <String> in front of the method name list clarifies and prevent error:

    f(new ArrayListGenerator().<String>list());  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top