Understanding upper and lower bounds on ? in Java Generics

后端 未结 6 497
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 01:45

I am really having a tough time understanding the wild card parameter. I have a few questions regarding that.

  1. ? as a type parameter can only

6条回答
  •  孤独总比滥情好
    2020-11-29 02:21

    For the first question: you can not define a method with ? as a type parameter either. The following will not compile:

    void  foo() {}
    

    ? is used for binding to another generics without providing the type parameter. You can write for methods:

    void foo(List e) {}
    

    And you can also write for classes:

    public class Bar> { }
    

    For the use of super:

    public void printAll(MyList){
        // code code code
    }
    

    This will not as you say print the list "if it has objects of MyClass". It can have objects of any class that is a subclass of a class that is a parent of MyClass. The compiler does not know at compile time what are the objects that will be in the list anyway.

    To get your head around it, consider a simple example with the Number class hierarchy. Float and Integer are children of Number. You can write your method like this:

    public void printAll(List){
        // code code code
    }
    

    Then you can call that method with a List:

    List numbers = new ArrayList<>();
    numbers.add(1); // actually only add an Integer
    printAll(numbers); // compiles.
    

    This is possible would not be super useful in that case. Where it would be useful for example is when you want to add Float to a collection without wanting it to be only a List, like:

    public void addFloat(List list){
        list.add(2.5);
    }
    

提交回复
热议问题