Bax
Bax

Reputation: 4506

Java generics return object instead of list

Out of pure curiosity, having :

List bigList = new ArrayList();

Why this code compiles :

List<List> partitions = Lists.partition(bigList , 10);
for (List partition : partitions) {}

And this does not :

for (List partition : Lists.partition(bigList , 10)) {}

?

Signature of partition method :

<T> List<List<T>> partition(List<T> list, int size)

Upvotes: 0

Views: 277

Answers (1)

BambooleanLogic
BambooleanLogic

Reputation: 8171

List<List> partitions = Lists.partition(bigList , 10);

Lists.partition(bigList , 10)

These two lines will do the exact same thing during runtime. The difference is during compile time where the former will be forcefully interpreted as a List<List> (with a compiler warning because it's a potentially dangerous thing to do) while the latter is assumed to be a raw List.

When iterating over a List<List>, the elements will be assumed to be List. For raw types though, the elements will be assumed to be Object. Therefore, this breaks:

for (List partition : Lists.partition(bigList , 10)) {}

...because you're trying to assign an Object to a List variable.

I would also like to reiterate what I mentioned in a comment: Don't use raw types unless you have a very good reason to do so and fully understand the risks and consequences of doing so. Due to Java's type erasure, using raw types will make you lose all guarantees that a list contains what it claims to contain, potentially making the entire program crash if the wrong type is encountered.

Upvotes: 3

Related Questions