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

1

14

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?

Hazing answered 9/10, 2018 at 12:6 Comment(0)
B
16

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)
Bespatter answered 9/10, 2018 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.