Java-based generics

Use of generics:
1. Use generics in collections
2. Custom generic classes, generic interfaces, generic methods
3. Relationship between generics and inheritance
4. Wildcards

1> Generic class
public class DAO<T> {
    public void add(T t){
        ....
    }
}
specifies that this class serves a certain type of data

2> Generic method: put array elements into the collection
public <E> List<E> fromArryToList( E[] e,List<E> list){
    for(E e1 : e){
        list.add(e1);
    }
    return list;
}
        Integer[] inti = new Integer[]{1,2,3};
        List <Integer> list1 = new ArrayList<Integer>();
        List<Integer> list2 = order.fromArrayToList(inti, list1);
        System.out.println(list2);

3>Relationship between generics and inheritance
if A is B's subclass, then List<A> is not a subinterface of List<B>
List<Object> list1 = null;
List<String> list2 = new ArrayList<String>();

4>通配符 ?
List<A>、List<B>、、、、、、都是List<?>的子类
eg:
List<?> list = null;
List<Object> list1 = new ArrayList<Object>();
List<String> list2 = new ArrayList<String>();
list = list1;
list = list2;

Boolean addAll(Collection<? extends E> c);
可以放入E的本身或者E的子类
List<? extends Number> list = null;
        List<Integer> list1 = null;
        list = list1;

Boolean addAll(Collection<? supper A> a)
可以存放A本身及其父类
List<? super Number> list = null;
    List<Object> list1 = null;
    list = list1;① The static keyword cannot be used in the method

5> Pay attention to the use of generics

Reason: The generic type can only be determined when it is instantiated, so the static keyword cannot be used. 2. The
generic type cannot be declared in try{}catch(T e){}
3. Wildcards? The declared collection cannot add any elements to it. The exception is null.






Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326892630&siteId=291194637