Generic in this life and afterlife

1. What is generic?

     Java generics is a new feature introduced in JDK 5. Generics provide a compile-time type safety detection mechanism, which allows programmers to detect illegal types at compile time.

The essence of generics is a parameterized type, which means that the type of data being manipulated is specified as a parameter.

2. Why use generics?

①Strong type checking at compile time

② Eliminate explicit type casting

③Better code reusability, so as to achieve the effect of functional abstraction

3. Classification of generics

 Generally divided into: generic class, generic interface and generic method

3.1 Generic class

//将要操作的数据类型指定为参数T
public class Box<T> {
    private T t;
    
    public void add(T t) {
        this.t = t;
    }
    
    public T get() {
        return this.t;
    }
}

3.2 Generic methods

public static <T> List<T> findRepeat(Collection<T> datas) {
        if (datas instanceof Set) {
            return new ArrayList<>();
        }
        HashSet<T> set = new HashSet<>();
        List<T> repeatList = new ArrayList<>();
        for (T t : datas) {
            if (set.contains(t)) {
                repeatList.add(t);
            } else {
                set.add(t);
            }
        }
        return repeatList;
    }

3.3 Generic interface

public interface IStrategy {

    /**
     * 根据id获取对应的图表数据
     * @param dispatchQuery
     * @return
     */
    <T> T getGraphData(DispatchQuery dispatchQuery);
}

Note: If you need to use generics, you first need to use <T> to declare that it is generic. Of course, you can use other <E>s. Generally, using <T> is more common.

4. Wildcard Generics

Wildcards can be restricted using the extends and super keywords:

extend

The upper bound is declared with the extends keyword, indicating that the parameterized type may be the specified type or a subclass of this type.

super

The lower bound is declared with super, indicating that the parameterized type may be the specified type, or the parent type of this type, up to Object.

4.1 List<? extends Apple> means uncertain parameter type, but must be Apple type or Apple subclass type, which is the upper boundary limit

4.2 List<? super Apple> indicates that the parameter type is uncertain, but it must be the Apple type or the parent type of Apple, which is the lower boundary limit

4.3 List<?> represents an unrestricted wildcard, which is equivalent to List<? extends Object>

The specific difference between the two: https://blog.csdn.net/qq_32117641/article/details/88692100?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none- task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

 

 

Guess you like

Origin blog.csdn.net/zhangxing52077/article/details/106712619