new ImmutableMap.Builder() vs ImmutableMap.builder()

Viewed 501

enter image description here

private static final Map<String, String> LOCALE_FOLDER_MAP = new ImmutableMap.Builder()
        .put("a", "b")
        .build();

private static final Map<String, String> LOCALE_FOLDER_MAPP = ImmutableMap.builder()
        .put("a", "b")
        .build();

It is strange ImmutableMap.builder() returns new ImmutableMap.Builder();. After replacing the original code using the return statement, the above two code segments should be equivalent.

But it does not, which confuses me.

Does anyone have explanations?

The error message is

Required type: Map <String, String>. Provided: ImmutableMap<Object, Object>

2 Answers

ImmutableMap.builder is generic. You need to provide arguments to it. Otherwise it will infer ImmutableMap.Builder<Object, Object> as its return type.

ImmutableMap.<String, String>builder() should do the trick.

First one is working because apparently you can assign raw type to paramtrized.

ImmutableMap v1 = ...;
ImmutableMap<String, String> v2 = v1;

Not answering the original question, but if you are using Java 9 (or later) you can use Java's standard library Map.of() to create an immutable map:

private static final Map<String, String> LOCALE_FOLDER_MAP = Map.of("a", "b");
Related