[英]Method reference on map function, compilation error when the key is of type String
Context : 背景 :
I want to use the function computeIfAbsent
on a Map
. 我想在
Map
上使用computeIfAbsent
函数。 But, I get a compilation error when I use 但是,当我使用时,我收到编译错误
String
. String
。 I get no compilation error when I use 我使用时没有编译错误
Integer
. Integer
。 String
. String
。 Illustration : 插图 :
The following statements are legal : 以下陈述是合法的 :
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
The following statements are illegal : 以下陈述是非法的 :
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
The following statements are legal : 以下陈述是合法的 :
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
Question : I don't get why a String
as key is that special when combined with method reference. 问题 :当结合方法引用时,我不明白为什么
String
作为键是特殊的。 Any idea? 任何的想法?
When you call ArrayList::new
instead of x -> new ArrayList<>()
it's equals to call x -> new ArrayList<>(x)
. 当你调用
ArrayList::new
而不是x -> new ArrayList<>()
它等于调用x -> new ArrayList<>(x)
。
Method computeIfAbsent
requires lambda expression with one lambda parameter as second input argument, or a reference to method that consumes one argument of String
type. 方法
computeIfAbsent
需要lambda表达式,其中一个lambda参数作为第二个输入参数,或者对使用String
类型的一个参数的方法的引用。
Your error 你的错误
Compilation error: The type ArrayList does not define ArrayList(String) that is applicable here
编译错误:类型ArrayList未定义此处适用的ArrayList(String)
is talking: you trying to call constructor with one String argument
. 正在谈论:
you trying to call constructor with one String argument
。 Because, as I told above, lambda x -> someObject.method(x)
is equal to someObject::method
. 因为,正如我上面所说,lambda
x -> someObject.method(x)
等于someObject::method
。 Or lambda x -> new SomeClass(x)
is equal to SomeClass::new
. 或者lambda
x -> new SomeClass(x)
等于SomeClass::new
。
You can't use method (constructor) reference here, because here required method (constructor) that consumes one parameter, or a lambda expression. 你不能在这里使用方法(构造函数)引用,因为这里需要使用一个参数或一个lambda表达式的方法(构造函数)。 If there was lambda without any parameters, you will be able to call empty constructor.
如果有lambda没有任何参数,你将能够调用空构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.