How to enable List <Map <?,? >> in List <Map <String, String >>?

I am creating a bukkit plugin and one function returns List<Map<?, ?>> if I do this:

 List<Map<String, String>> circle = FileManager.area.getMapList("circles"); 

I get an error that cannot be converted. What to do?

Error:

 List<Map<?, ?>> cannot be converted into List<Map<String, String>> 
+5
source share
4 answers

You can drop all generics by switching to the original type, (List) :

 List<Map<String, String>> circle = (List) FileManager.area.getMapList("circles"); 

Please note that, as in most cases, this is unsafe - it’s better to find a way to pass the correct type information, as other answers indicate.

+6
source

getMapList returns the type List<Map<?, ?>> into List<Map<String, String>> . Since generics are invariant, you need to map types

 List<Map<?, ?>> circle = FileManager.area.getMapList("circles"); 
+1
source

Map<String, String> is a subtype of Map<?, ?> , But since generics are not invariant, this does not mean that List<Map<String, String>> is a subtype of List<Map<?, ?>> .

If you are sure that all keys and values ​​are String instances, you can do this

 List<Map<String, String>> circle = (List<Map<String, String>>) (Object) FileManager.area.getMapList("circles"); 

However, I would not recommend it, because if any of the keys or values ​​is not String , you can get a ClassCastException later, so that you throw away the guarantee that generic tools generate.

An alternative would be to create a new ArrayList<Map<String, String>>() and iterate over List<Map<?, ?>> , and then use instanceof to check all the keys and values ​​in each Map<?, ?> String . Only if the instanceof check is successful do you need to add an entry.

+1
source

It is mainly used for assigning from some specific value, for example: Map m = new HashMap ();

And the use is not very good, because you need to use it explicitly (this means that you know your type of runtime in advance).

Usually you explicitly specify the return values. So let's look at cases:

1) You want to write a very general function that receives a string and returns List>, then you can write like this

 <K, V> List<Map<K, V>> getMapList(String s) { ... } 

Java will infer the type K, V depending on what you assign.

2) You want to return a specific type, then use this type:

 <Integer, String> List<Map<Integer, String>> getMapList(String s) { ... } 
0
source

Source: https://habr.com/ru/post/1210497/


All Articles