在 return 语句中没有找到适用于 ArrayList<String> .toArray(String[]::new) 的方法

2022-09-04 21:03:52

我正在网站Codedingbat上工作,特别是AP-1中的这种方法

public String[] wordsWithout(String[] words, String target) {
  ArrayList<String> al = new ArrayList<>(Arrays.asList(words));
  al.removeIf(s -> s.equals(target));
  return al.toArray(new String[al.size()]);
}

此实现有效,并且它当前提交的内容,但是当我将 return 语句更改为

return al.toArray(String[]::new);

据我所知,这应该有效,给出以下错误:

no suitable method found for toArray((size)->ne[...]size])
method java.util.Collection.<T>toArray(T[]) is not applicable
  (cannot infer type-variable(s) T
    (argument mismatch; Array is not a functional interface))
method java.util.List.<T>toArray(T[]) is not applicable
  (cannot infer type-variable(s) T
    (argument mismatch; Array is not a functional interface))
method java.util.AbstractCollection.<T>toArray(T[]) is not applicable
  (cannot infer type-variable(s) T
    (argument mismatch; Array is not a functional interface))
method java.util.ArrayList.<T>toArray(T[]) is not applicable
  (cannot infer type-variable(s) T
    (argument mismatch; Array is not a functional interface)) line:4

有人会好心解释为什么这不起作用吗?


答案 1

这:

al.toArray(String[]::new)

仅支持 java-11,通过以下方式:

default <T> T[] toArray(IntFunction<T[]> generator) {
     return toArray(generator.apply(0));
}

如果要使用该方法引用,则必须首先执行以下操作:stream()

 al.stream().toArray(String[]::new)

答案 2

推荐