Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 564
FreakyDan Avatar asked Dec 20 '22 12:12

FreakyDan


2 Answers

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;
like image 56
Markus A. Avatar answered Dec 28 '22 23:12

Markus A.


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.

like image 29
Smith_61 Avatar answered Dec 28 '22 23:12

Smith_61