What is the difference between <? extends Base> and ?

前端 未结 4 1531
温柔的废话
温柔的废话 2021-02-01 03:24

In this example:

import java.util.*;

public class Example {
    static void doesntCompile(Map> map) {}
    static &l         


        
4条回答
  •  一生所求
    2021-02-01 04:22

    I'd recommend you to look in documentation of generic wildcards especially guidelines for wildcard use

    Frankly speaking your method #doesntCompile

    static void doesntCompile(Map> map) {}
    

    and call like

    doesntCompile(new HashMap>());
    

    Is fundamentally incorrect

    Let's add legal implementation:

        static void doesntCompile(Map> map) {
            List list = new ArrayList<>();
            list.add(0.);
            map.put(0, list);
        }
    

    It is really fine, because Double extends Number, so put List is absolutely fine as well as List, right?

    However, do you still suppose it's legal to pass here new HashMap>() from your example?

    Compiler does not think so, and is doing his (its?) best to avoid such situations.

    Try to do the same implementation with method #compile and compiler will obviously does not allow you to put a list of doubles into map.

        static  void compiles(Map> map) {
            List list = new ArrayList<>();
            list.add(10.);
            map.put(10, list); // does not compile
        }
    

    Basically you can put nothing but List that's why it's safe to call that method with new HashMap>() or new HashMap>() or new HashMap>() or new HashMap>().

    So in a nutshell, you are trying to cheat with compiler and it fairly defends against such cheating.

    NB: answer posted by Maurice Perry is absolutely correct. I'm just not sure it's clear enough, so tried (really hope I managed to) to add more extensive post.

提交回复
热议问题