When implementing a Stream-class using a delegate stream, I get strange warning by IntelliJ:
Array of type
java.lang.Object[]expected,A[]found
The code which triggers the warning:
public class MyStream<T> implements Stream<T> {
private final Stream<T> delegate;
public MyStream(Stream<T> delegate) {
this.delegate = delegate;
}
*snip*
@Override
public <A> A[] toArray(IntFunction<A[]> generator) {
return delegate.toArray(generator);
}
*snip*
}
The full warning:
Array of type
java.lang.Object[]expected,A[]foundInspection info: Reports two types of suspicious calls to
Collection.toArray(). The first type is any calls where the type of the specified array argument is not of the same type as the array type to which the result is casted. Example:void m(List list) { Number[] ns = (Number[]) list.toArray(new String[0]); }The second type is any calls where the type of the specified array argument does not match the type parameter of the collection declaration. Example:
void m(List<Number> list) { Number[] ns = list.toArray(new String[0]); }
I somewhat assume this is a false positive, caused by type erasure, mostly because I cannot find any sane reason why this would cause a problem, and also because the examples from the warning do not match very well with my code.
However, when thinking about it, I wondered: If this is a false positive triggered because of type erasure, why does it know about A at all? Also, Java does usually cast a A[] to a Object[] implicitly, so why doesn't it here?
So: What is happening here?