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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With