map函数的方法引用,key为String类型时编译报错

Method reference on map function, compilation error when the key is of type String

上下文:

我想在 Map 上使用函数 computeIfAbsent。但是,当我使用

时出现编译错误

我使用时没有编译错误

插图:

以下声明合法

Map<Integer, List<Long>> map = new HashMap<>();
Integer key = Integer.valueOf(0);
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // No compilation error

以下语句非法

Map<String, List<Long>> map = new HashMap<>();
String key = "myKey";
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // Compilation error: The type ArrayList does not define ArrayList(String) that is applicable here

以下声明合法

Map<String, List<Long>> map = new HashMap<>();
String key = "myKey";
Long value = Long.valueOf(2);
map.computeIfAbsent(key, x -> new ArrayList<>()).add(value); // No compilation error

问题: 我不明白为什么 String as key 在与方法引用结合使用时如此特殊。有什么想法吗?

当您调用 ArrayList::new 而不是 x -> new ArrayList<>() 时,它等于调用 x -> new ArrayList<>(x).

方法 computeIfAbsent 需要带有一个 lambda 参数的 lambda 表达式作为第二个输入参数,或者对使用一个 String 类型参数的方法的引用。

你的错误

Compilation error: The type ArrayList does not define ArrayList(String) that is applicable here

正在说话:you trying to call constructor with one String argument。因为,正如我上面所说,lambda x -> someObject.method(x) 等于 someObject::method。或者 lambda x -> new SomeClass(x) 等于 SomeClass::new

你不能在这里使用方法(构造函数)引用,因为这里需要使用一个参数的方法(构造函数),或者一个lambda表达式。如果有没有任何参数的 lambda,您将能够调用空构造函数。