java8 Generics

Generic, i.e. the parameters of the type and in the use of the class or type of method can be passed, without requiring a complete can be implemented to create new types of parameters controlled by the generic shape type. It can be used in a generic classes, methods, and interfaces.

1, the relevant generic operator

Using generic code often see some generic symbols related to their effect shown in the following table:

Types of Features
T,E,K,V Generic identity may be written into any identification, a different letter convention more, equivalent to <T extends Object>
? Unrestricted wildcard to indicate uncertainty about the type, equivalent to <? Extends Object>
extend Upper bound wildcard
super Lower bound through Hythe
& Additional constraints (AdditionalBound, tjls8-4.4)

2, an example of basic use generics

public class GenericDemo<C> { //泛型类

    public static void main(String[] args) {
        //泛型类用Integer初始化,所以C相关的方法属性必须是Integer
        GenericDemo<Integer> gd = new GenericDemo<Integer>();
        gd.classPrint(1);
        gd.setX(2);
        //----------------------
        //泛型方法,与调用的类型保持一致,参数类型得为String
        GenericDemo.<String>methodPrint("abc");
        //---------------------
        //泛型接口,与初始化时候传入的类型保持一致,参数类型得是Double
        IFC<Double> ifc = new IFC<Double>() {};
        ifc.interfacePrint(2.9);
    }

    private C c;

    public void setX(C c) {
        this.c = c;
    }
        public void classPrint(C c) {
        System.out.println(c.getClass());
    }

    //泛型方法,前面的<T>是为了标识这是一个泛型方法
    public static <T> void methodPrint(T t) {
        System.out.println(t.getClass());
    }

    interface IFC<I> { //泛型接口
        default void interfacePrint(I i) { System.out.println(i.getClass());}
    }
}

3, Tsuhaifu

Difference 3.1, T and? A

T is a basic generic definition of the data type parameter, it can not be used to instantiate. And? It is uncertain when the generic types of specific parameters when instantiating an object Object refers to all subtypes.

Types of Feature
T <T extends Object>, is used to define
? <? Extends Object>, used to instantiate

? Object can not equivalent, ? Argument type is not a type parameter, it is used in a general argument types , when the particular type of uncertainty can be used? , For example:

public class test6 {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        test(list1);
        test(list2);
    }

    public static void test(List<?> list) {
        System.out.println(list);
    }
}

3.2, the upper and lower boundaries through Hythe

Upper and lower bounds wildcards in fact related to the java polymorphic properties, the feasibility of restructuring and down, subclass instance can be converted into a class instance of the parent, but the parent class instance is not necessarily converted into a sub-class instance, only the sub-class instance itself is up examples of parent transformation can downcast subclasses.

<? Extends T> T represents the type and the range of its subclasses, <? Super T> T represents the type and the range of their parent classes.

Wildcard limits when applied to a set of read and write will affect the behavior of the collection:

The upper bound of <? Extends T> limit the type of ceiling can only upward transition, can be read, but not write, because the sub-type of uncertainty, not downcast;

The lower bound of <? Super T> type of limit lower limit, only downcast, you can write, but can not read, because the parent type of uncertainty, not upward transition.

Example:

public class test {

    public static void main(String[] args) {
        //<? extends B> 范围: A类或者A的子类
        //由于下限不确定,所以无法向下转型至具体类型
        List<? extends B> list1 = new ArrayList<B>(){{add(new B());}};
//        list1.add(new B()); //无法添加该类型, 向下转型无法确定目标类型
//        list1.add(new C());
        A a = list1.get(0); //正常向上转型

        //<? super B> 范围: B类或者B的父类
        //由于上限不确定,所以B类和B类的子类均可以加入,但是B类的父类不行
        List<? super B> list2 = new ArrayList<>();
//        list2.add(new A()); //无法向下转型
        list2.add(new B()); //正常向上转型
        list2.add(new C());
//        C c = list2.get(0);//无法向下转型,不加强制转换会报错
        C c = (C)list2.get(0);
    }
    //   A -> B -> C
    static class A {};
    static class B extends A {};
    static class C extends B {};
}

4, additional constraints (&)

AdditionalBound the following syntax:

TypeBound:
extends ClassOrInterfaceType {AdditionalBound}
AdditionalBound:
& InterfaceType

That extends behind the additional constraints may be added, particularly as the interface type, can I1 & I2 & I3 platoon Thus, the interface must be noted that the type, class or type is not variable, there is an additional constraint limiting effect type must implement associated interface, for example:

public class test {

    public static void main(String[] args) {
        test1(1); test1("1");
        test2(2); test2("2");
//        test3(3);  //test3方法String类型才满足额外约束
        test3("3");
    }

    public static <T extends Object> void test1(T t) {
        System.out.println(t.getClass());
    }
    //得同时实现Serializable和Comparable接口
    public static <T extends Object & Serializable & Comparable> void test2(T t) {
        System.out.println(t.getClass());
    }
    //得同时实现Serializable,CharSequence和Comparable接口
    public static <T extends Object & Serializable & CharSequence & Comparable> void test3(T t) {
        System.out.println(t.getClass());
    }
}

Further, additional constraints can be used for type casting:

public class test12 {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static Object test() {
//        return (Object & Number)"abced"; //编译不通过
//        return (Object)"abced"; //编译通过
        return (Object & CharSequence & Comparable)"abcde"; //编译通过
    }
}

In some types of scene conversion range of conversion can be controlled by the type of additional constraints.

Reference links:

https://codeday.me/bug/20190313/767875.html

https://juejin.im/post/5b614848e51d45355d51f792

https://www.cnblogs.com/whatlonelytear/p/11055126.html

https://blog.csdn.net/s10461/article/details/53941091

https://blog.csdn.net/claram/article/details/51943742

Guess you like

Origin www.cnblogs.com/cord/p/11616353.html