上下文:
我想在 Map
上使用函数 computeIfAbsent
。但是,当我使用
- 方法引用,键是一个
String
。
我在使用时没有编译错误
- 方法引用,键是一个
Integer
。 - lambda,键是
String
。
插图:
以下声明合法:
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
作为键在与方法引用结合使用时如此特殊。有什么想法吗?
最佳答案
当您调用 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,您将能够调用空构造函数。
关于java - map函数的方法引用,key为String类型时编译报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024007/