Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 528
Alex Pickering Avatar asked Oct 09 '18 12:10

Alex Pickering


People also ask

How do you return an ArrayList as a string?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.

Is ArrayList zero based?

Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null . Elements in the ArrayList are accessed via an integer index. Indexes are zero-based.


1 Answers

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)
like image 92
Eugene Avatar answered Sep 19 '22 01:09

Eugene