关于map函数的方法参考,当键的类型为String时编译错误

Key*_*r00 3 java lambda compiler-errors hashmap method-reference

背景:

我想computeIfAbsent在a上使用该功能Map.但是,当我使用时,我收到编译错误

  • 方法参考和关键是一个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
Run Code Online (Sandbox Code Playgroud)

以下陈述是非法的:

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
Run Code Online (Sandbox Code Playgroud)

以下陈述是合法的:

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
Run Code Online (Sandbox Code Playgroud)

问题:String当与方法引用结合使用时,我不明白为什么关键是特殊的.任何的想法?

Pet*_*hin 5

当你打电话ArrayList::new而不是x -> new ArrayList<>()它等于打电话x -> new ArrayList<>(x).

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

你的错误

编译错误:类型ArrayList未定义此处适用的ArrayList(String)

在说: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没有任何参数,你将能够调用空构造函数.

  • 你的回答给了我需要的提示:在ArrayList类中只有以下构造函数:ArrayList(),ArrayList(Collection <?extends E> c),ArrayList(int initialCapacity).谢谢 (2认同)