Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

java - Double brace initialisation (anonymous inner class) with diamond operator

I am wondering why the second map declaration (using the diamond operator) does not compile when the first one does. Compilation error:

error: cannot infer type arguments for HashMap; Map map2 = new HashMap<>() { reason: cannot use '<>' with anonymous inner classes where K,V are type-variables: K extends Object declared in class HashMap V extends Object declared in class HashMap

Code:

    Map<String, String> map1 = new HashMap<String, String>() { //compiles fine

        {
            put("abc", "abc");
        }
    };

    Map<String, String> map2 = new HashMap<>() { //does not compile

        {
            put("abc", "abc");
        }
    };

EDIT
Thanks for your answers - I should have read the compilation error better. I found the exaplanation in the JLS

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't have a static initializer here (the keyword static is missing altogether).

Basically you create a new anonymous subclass of HashMap and define the instance intializer block here. Btw, this only works since HashMap is not final.

Since you'll get an anonymous subclass of HashMap the diamond operator doesn't work here, since the subclass would then be compiled as if you wrote ... extends HashMap<Object, Object> and this clearly isn't compatible to Map<String, String>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...