作者:万象新动HR | 来源:互联网 | 2022-12-02 17:43
我正在使用Codingbat网站,特别是AP-1中的这种方法
public String[] wordsWithout(String[] words, String target) {
ArrayList 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.toArray(T[]) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; Array is not a functional interface))
method java.util.List.toArray(T[]) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; Array is not a functional interface))
method java.util.AbstractCollection.toArray(T[]) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; Array is not a functional interface))
method java.util.ArrayList.toArray(T[]) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; Array is not a functional interface)) line:4
有人会这么好解释为什么这不起作用?
1> Eugene..:
这个:
al.toArray(String[]::new)
仅在java-11之后支持:
default T[] toArray(IntFunction generator) {
return toArray(generator.apply(0));
}
如果你想使用那个方法参考,你必须stream()
首先,如:
al.stream().toArray(String[]::new)