在return语句中找不到适合ArrayList <string> .toArray(String [] :: new)的方法

时间:2018-10-09 12:06:02

标签: java arraylist lambda java-8 toarray

我正在Codingbat网站上工作,特别是在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 个答案:

答案 0 :(得分:12)

此:

al.toArray(String[]::new)
从Java-11开始仅通过以下方式支持

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

如果要使用该方法引用,则必须先stream(),例如:

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