Understanding upper and lower bounds on ? in Java Generics

后端 未结 6 502
佛祖请我去吃肉
佛祖请我去吃肉 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:15

    Lower-bound says: You can use the class mentioned after 'super' keyword, or any of its super types. This can get tricky. Those super types may have other (completely different) classes inheriting from them, as below example shows.

    Say,

    List cars = new ArrayList ();
    

    Should the programmer be allowed to write:

    cars.add(new Helicopter()); //Helicopter is a kind of Vehicle
    

    That should obviously not be allowed, and it reflects a danger in using lower-bounds.

    Programmer should be allowed to add a Vehicle to list, but not ANY Vehicle. He must cast it, to let Java know he is only adding a Car Vehicle after all, like this:

    cars.add((Car) new Vehicle()); 
    

提交回复
热议问题