Andy Andy - 1 year ago 130
Java Question

cast List<Object> to List<Map<String, Object>>

I should know this, but I can't understand this for some reason.

Why can I not cast a List of Objects

to a List of Maps
List<Map<String, Object>>
? Every object in the list is an object of type
Map<String, Object>
, so why is the casting not possible?

What I can do is create a
new ArrayList<Map<String, Object>>();
and iterate over the list and add each item with a cast.

List<Object> dataList;
//Why doesn't this work?
List<Map<String, Object>> rxData = (List<Map<String, Object>>)dataList;

//This works, but is there a better way?
rxData = new ArrayList<Map<String, Object>>();
for (Object data : dataList) {
rxData.add((Map<String, Object>)data);

Answer Source

You can just drop generic parameter by double-casting:

List<Map<String, Object>> rxData = (List<Map<String, Object>>) (List<?>) dataList;

What is going here is that you force compiler to not to check generic type by omitting it with first cast and then do unchecked cast to List<Map<String, Object>>. This is possible because java generics is non-refiable.

The original error is caused by fact that Object is not compatible with Map<> type and there is no such thing like covariant/contravariant types in java (unlike scala for example).

But there gonna be a problems if dataList contains not maps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download