7

In JDK 1.7 I can create a Collection lets for e.g. say a HashMap like this:

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

With the diamond <> at the end.

But if I am creating a map like this:

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

On the diamond compiler says that:

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

I have to use: ... new HashMap<String, String>() {{.... in order the code to compile.

Why is it so? Why I can create a map and use diamond if I am creating just a new instance but the code doesn't compile if I am creating a map through an anonymous class?

1 Answers1

4

This is just a guess but when you do

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

It actually creates a subclass of HashMap I don't like this because you dirty up your classes with a bunch of subclasses. I am guessing in this case Java cannot infer what the generic diamond type is because it is being subclassed.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • 3
    but I think the question OP is asking is *why* is Java unable to infer it in this case? – matt b Feb 14 '13 at 15:59
  • @mattb *It actually creates a subclass of `HashMap`* – Luiggi Mendoza Feb 14 '13 at 16:00
  • Yep, but as said on http://stackoverflow.com/questions/9773733/double-brace-initialisation-anonymous-inner-class-with-diamond-operator it is also because of subclassing. That question doesn't have an answer either to why though. – Amir Raminfar Feb 14 '13 at 16:00
  • @AmirRaminfar Actually the accepted answer for that question does offer a reason to why: "the subclass would then be compiled as if you wrote `... extends HashMap` and this clearly isn't compatible to `Map`." – matts Feb 14 '13 at 16:02
  • @matts that's right I missed that. – Amir Raminfar Feb 14 '13 at 16:04