java generics and wildcards (?)

Generics apply to the declaration of a generic class or a generic method.

such as class GenericTest

public class GenericTest<T> {

    private T item;
    public void set(T item) {
        this.item = item;
    }
    public T get() {
        return item;
    }
}

When there is this class to generate an object, you can select the corresponding type, GenericTest<Integer> test = new GenericTest<>(); GenericTest<String> test = new GenericTest<>();

Container classes are more common in java, such as List<Double> list = new ArrayList<>(), Map<Integer, String> map = new HashMap<>();

 

 

 Wildcards (?) applied to the use of generics

Wildcards are used to use defined generics, such as using the methods of the above generic classes,

    public void test(GenericTest<?> obj) {
        System.out.println(obj);
    }

For example, List<?> list = new ArrayList<String>(); In theory, ? can add any element to list, but List<?> cannot add any element to list (except null), list.add(" abc"); list.add(56); will report an error. Without being able to determine the type of the added element, the memory size cannot be allocated.

 

The more common ones are <? extends T> or <? super T> with bounded wildcards.

List<? extends T> indicates that the elements in the list are all subclasses of T and T, and List<? super T> indicates that the elements in the list are the parent classes of T and T.

 

Integer is a subclass of Number, but ArrayList<Integer> is not a subclass of ArrayList<Number>, and a list containing Number cannot contain Integer. ArrayList<Number> list = new ArrayList<Integer>(); // Error.

It is correct to change to ArrayList<? extends Number> list = new ArrayList<Integer>();

 

 

<? extends T> cannot be stored in, but can only be taken out.

List<? extends Number> list = new ArrayList<>();

list.add(3); // error
list.add(2.2); // error

Number n = list.get(0); //correct
float f = (float)list.get(1); //correct

(Conjecture) Since the size of the memory occupied by the subclass object is >= the parent class object, it is not possible to allocate an appropriate memory size for the object when adding elements to the list. The elements in the list are all Number and its subclasses, so the extracted elements can be converted to the Number class.

 

 

<? super T> can be stored in or taken out.

List<? super Integer> list = new ArrayList<>();

list.set(0, 2);                   // correct

int a = (int)list.get(0);     // correct

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325281544&siteId=291194637