Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast List<Object> to List<Map<String, Object>> [duplicate]

Tags:

java

hashmap

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

Why can I not cast a List of Objects List<Object> 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);
}
like image 430
Andy Avatar asked Apr 07 '26 03:04

Andy


1 Answers

You can just drop generic parameter by double-casting:

@SuppressWarnings("‌​unchecked")
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.

like image 193
vsminkov Avatar answered Apr 08 '26 16:04

vsminkov