No suitable method found for ArrayList<String> .toArray(String[]::new) in return statement

Alex Pickering :

I am working on the site Codingbat, specifically this method in 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()]);
}

This implementation works, and its what is currently submitted, but when I change the return statement to

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

which should work as far as I know, gives the following error:

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

Would anyone be so kind as to explain why this doesn't work?

Eugene :

This:

al.toArray(String[]::new)

is only supported since java-11 via:

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

If you want to use that method reference, you would have to stream() first, like:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36646&siteId=1