Definition of upper and lower bounds in generics
Upper bound extend Fruit>
Lower bound< ? super Apple>
Characteristics of upper bounds and lower bounds
The upper bound list can only be get, not add (to be precise, it cannot add anything other than null) Objects, including Object)
The lower bound list can only be added, but not get
import java.util.ArrayList; import java.util.List; class Fruit {} class Apple extends Fruit {} class Jonathan extends Apple {} class Orange extends Fruit {} public class CovariantArrays { public static void main(String[] args) { //上界 List<? extends Fruit> flistTop = new ArrayList<Apple>(); flistTop.add(null); //add Fruit对象会报错 //flist.add(new Fruit()); Fruit fruit1 = flistTop.get(0); //下界 List<? super Apple> flistBottem = new ArrayList<Apple>(); flistBottem.add(new Apple()); flistBottem.add(new Jonathan()); //get Apple对象会报错 //Apple apple = flistBottem.get(0); } }
The reason for these characteristics
Upper bound extend Fruit> ; , indicates all subclasses that inherit Fruit, but which subclass it is cannot be determined, so when calling add, no one knows what type to add. But when getting, no matter what subclass it is, no matter how many generations it goes back, there must be a parent class called Fruit. Therefore, I can use the largest parent class, Fruit, to continue, that is, transform all subclasses upward into Fruit.
Lower bound super Apple> means that all parent classes of Apple, including Fruit, can be traced back to the ancestor Object. Then when I add, I can't add Apple's parent class, because I can't determine which parent class is stored in the List. But I can add Apple and its subclasses. Because no matter what type my subclass is, it can be transformed upward to Apple and all its parent classes or even to Object. But when I get it, there are so many parent classes of Apple. What should I use to continue it? Except for Object, I can’t catch anything else.
So, in the final analysis, it can be expressed in one sentence, that is, the compiler can support upward transformation, but does not support downward transformation. Specifically, I can assign the Apple object to a reference to Fruit, but if I assign the Fruit object to a reference to Apple, I must use cast
The above is the detailed content of Upper bound (extend) and lower bound (super) in java generics. For more information, please follow other related articles on the PHP Chinese website!