Java - Why can't I partially type a variable?

164 views Asked by At

Why when typing a new variable with an existing variable is typing all or nothing?

For example, say I have a variable data whose type is List<Map<String, ArrayList<String>>>, and I want to pass its value to tempData. Why when deciding tempData's type am I limited to List or List<Map<String, ArrayList<String>>>?

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

I have searched my textbook and this site, but I can't find anywhere that explains why this is. Is there something that could go wrong if we were allowed to "partially-type"?

I know I can just strongly type tempData to begin with, but I am curious as to why Java has an all or nothing approach.

2

There are 2 answers

0
Markus A. On BEST ANSWER

Actually, you can: The trick is to use ? and ? extends in your declarations. The following works and gets progressively 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;
0
Smith_61 On

You can use java generics in order to replace types that you don't need full type information on. Similar to this

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

This will let you work with both the list and map type fully without knowing what the key and value types are for the map, but you can not operate on the types contained within the map without more type information.