C.LS
C.LS

Reputation: 1357

Why after using collect on a streamed list without generic returns an object?

Why the following code produces an object instead of a list ?

Object listWithoutGeneric = new ArrayList().stream().collect(Collectors.toList());

(trying to substitude Object listWithoutGeneric = ... with List listWithoutGeneric = ... produces compilation error)

while the following sample returns a list?

List listWithDefaultGeneric = new ArrayList<>().stream()
                                    .collect(Collectors.toList());

Upvotes: 4

Views: 73

Answers (1)

Eran
Eran

Reputation: 393841

Your terminal operation - collect - has the following signature:

<R, A> R collect(Collector<? super T, A, R> collector)

i.e. it returns an instance of type R.

The toList() Collector returns a Collector<T, ?, List<T>>, so R in that case is a List<T>.

However, if you are creating a Stream from a raw ArrayList, the Stream is also raw, so R becomes Object.

In other words, <R, A> R collect(Collector<? super T, A, R> collector) becomes Object collect(Collector collector), so collect returns an Object.

Hence new ArrayList().stream().collect(Collectors.toList()) returns an Object.

Upvotes: 6

Related Questions