Creating a map through an anonymous class using <>

In JDK 1.7, I can create Collectionlet for, for example. let's say a HashMapas follows:

private HashMap<String, String> map = new HashMap<>();

With a diamond <>at the end.

But if I create a map like this:

private static final HashMap<String, String> MAP = new HashMap<>() {{
    put("something", "something");
}};

In brilliant, the compiler says that:

Cannot use ''<>'' with anonymous inner classes

I need to use: ... new HashMap<String, String>() {{....to compile code.

Why is that? Why can I create a map and use a diamond if I only create a new instance, but the code does not compile if I create a map through an anonymous class?

+5
source share
1 answer

This is just a guess, but when you do

new HashMap<>() {{
    put("something", "something");
}};

HashMap , . , Java , , .

+2

All Articles