Anuj Garg Anuj Garg - 11 months ago 52
Java Question

Casting List<T> to List<String> type

I am casting List <T> to List <String>. getClass() method on any element of list returns the actual class of element of List i.e T rather than String. Shouldn't Java return String instead of actual class, as the list was casted to list of String?

public cast (List<?> unsortedList) {
List<String> unsortedListOfPrimitives = (List<String>)unsortedList;

cast(List<BigDecimal> unsortedList);

Output : java.math.BigDecimal

Answer Source

Java generics don't always work the way you'd expect.

Specifically, casting a generic to a specific type doesn't actually change the object, and you can get unsafe results when you do this and aren't 100% sure that you have it right.

So the object you have cast to List<String> is still actually a list containing BigDecimal entries, you have just mis-cast it.

This is a case where Java is type-unsafe - just as casting an Object to Integer is type-unsafe.