Search code examples
javastrong-typingweak-typing

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.


Solution

  • 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;