Java Why can't I partially enter a variable?

Why, when entering a new variable with an existing variable, is it all or nothing?

For example, let's say I have a variable datawhose type List<Map<String, ArrayList<String>>>, and I want to pass its value tempData. Why when choosing type tempDataam limits me Listor List<Map<String, ArrayList<String>>>?

If I want to interact only with a certain level of "t20", say, at a level Map, how can I just go there? For example, why can't I List<Map> tempData = data?

I was looking for my tutorial and this site, but I can not find anywhere that explains why this is so. Is there anything that could go wrong if we are allowed to "partially dial"?

I know that I can just type very hard tempDatato start, but I'm curious why in Java everything or nothing fits.

+4
source share
2 answers

Actually, you can : the trick is to use ?, and ? extendsyour ads. The following works and become more specific:

List<Map<String, ArrayList<String>>> data = null; // Replace null with content

Object temp1 = data;
List<?> temp2 = data;
List<? extends Map<?, ?>> temp3 = data;
List<? extends Map<String, ?>> temp4 = data;
List<? extends Map<String, ? extends ArrayList<?>>> temp5 = data;
List<Map<String, ArrayList<String>>> temp6 = data;
+10
source

You can use java generics to replace types with which you do not need complete type information. Like this

public static < K, V > List< Map< K, V > > test( List< Map< K, V > > list ) {
    return list;
}

This will allow you to work with the complete list and type of map without knowing what types of keys and values ​​are for the map, but you cannot work with the types contained on the map without additional information about the type.

+1
source

All Articles