Generic notes

Posted by edsmith on Thu, 23 Dec 2021 03:58:55 +0100

1, What is generics?

Generic: when a class is defined, it does not set the data type for the properties and methods (return values and parameters) in the class. When creating the object of the class, it specifies the corresponding data type.

2, Why use generics?

Example: define a point class, attribute: x coordinate and y coordinate

Requirements: values of x and y coordinates

(1) The values of the x and y coordinates are both integer.

(2) The values of x and y coordinates are decimal.

(3) The values of the x and y coordinates are strings.

Think about: types of x and y attributes. Object, because object is the parent of all classes, because of polymorphism

public class Test01 {
    public static void main(String[] args) {
        Point p1=new Point(15,25);// Values are integers
        Point p2=new Point(15.5,25.5);// Values are decimal
Point p3=new Point("150 degrees east longitude", "30 degrees north latitude")// Values are strings

        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }
}
//Thinking: I can create a Point object whose x coordinate is an integer and y coordinate is a string when assigning values. Will this program report an error. [no]
//It breaks the security problem of data type consistency.
class Point{
     private Object x;
     private Object y;

    public Point() {
    }

    public Point(Object x, Object y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

    public Object getX() {
        return x;
    }

    public void setX(Object x) {
        this.x = x;
    }

    public Object getY() {
        return y;
    }

    public void setY(Object y) {
        this.y = y;
    }
}

To solve the security problem of data type consistency, use generics.

3, Generic format

public class name < T, E... > {/ / T, E are generic flags

public # T # attribute name;

        public  T  getXXX(){}

        public void  setXXX(T  t){}

}

        

public class Test02{
    public static void main(String[] args) {
         Point<Integer> p1=new Point<>(15,25);
         Point<Double> p2=new Point<>(15.5,25.5);
         Point<String> p3=new Point<>("150 degrees east longitude","300 degrees north latitude");

         Point p4=new Point();//If the type is not set for generics, it defaults to Object

        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }
}
//T: It is customary to use t for generic representation. Type
class Point<T>{
     private T x;
     private T y;

    public Point() {
    }

    public Point(T x, T y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

    public T getX() {
        return x;
    }

    public void setX(T x) {
        this.x = x;
    }

    public T getY() {
        return y;
    }

    public void setY(T y) {
        this.y = y;
    }
}

4, Wildcard

Reference passing of objects is the most common in development, but in the operation of generic classes, the generic types must match before reference passing, otherwise they cannot be passed.

public class Test03 {
    public static void main(String[] args) {
            Info<Integer> i=new Info<>();
            i.setVar(15);
            fun(i);

            Info<Double> j=new Info<>();
            j.setVar(15.5);
            fun(j); //Reference type passing of generics requires type matching and generics to match.
           //Think: can generics let him pass arbitrary types? You can not write or use wildcards.
    }
    public static void fun(Info<?> a){
         a.show();
    }
}

class Info<T> {
    private T var;//Member variable

    public void setVar(T var) {
        this.var = var;
    }

    public void show() {
        System.out.println("var=======" + var);
    }
}

5, Restricted generics

In reference passing, you can also set the upper and lower range limits of a generic object in a generic operation. The upper range limit is declared with the extends keyword, indicating that the parameterized type may be the specified type or a subclass of this type, while the lower range limit is declared with super, indicating that the parameterized type may be the specified type or the parent type of this type.

Format:

Set upper limit:

Declaration object: class name <? Extensions class > object name;

Definition class: [access rights] class name < generic ID > extends > {}

Set lower limit:

Declaration object: class name <? super class > object name;

Definition class: [access rights] class name < generic ID > super class > {}

public class Test04 {
    public static void main(String[] args) {
        Info<Integer> a=new Info<>(25);//Create an info object whose generic type is Integer
        fun1(a);
        Info<Number> b=new Info<>(25);
        fun1(b);
        Info<Double> f=new Info<>(25.5);
        fun1(f);
       //=======================================================
        Info<String> c=new Info<>("hello");
        fun2(c);
        Info<Object> o=new Info<>(true);
        fun2(o);
    }
    //Sets the Generic upper limit for the parameter.
    public static void fun1(Info<? extends Number> a){
         a.show();
    }
    //The lower bound of the generic is set. Must be a String or a parent class of String
    public static void fun2(Info<? super String> b){
        b.show();
    }
}

class Info<T> {
    private T var;

    public Info(T var) {
        this.var = var;
    }

    public void show() {
        System.out.println("var======" + var);
    }
}

6, Generic interface

At jdk1 After 5, you can declare not only generic classes, but also generic interfaces. The syntax of declaring generic interfaces is similar to that of declaring generic classes. You also add < T > after the interface name. The format is as follows:

[access authority] interface , interface name < generic ID >{

}

6.1 two implementation methods of generic interface

After defining a generic interface, you need to define subclasses of the interface. There are two ways to define subclasses of a generic interface

① Declare generics directly after subclasses

② The generic type is directly given in the interface implemented by the subclass

public class Test05 {
    public static void main(String[] args) {
         USB<Integer> a=new Upan<>();

         USB<String> b=new Mouse();
    }
}
//Generic interface.
interface USB<T>{

    public T show();

}
//This generic type is also used when the class is created
class Upan<T> implements USB<T>{
    @Override
    public T show() {
        return null;
    }
}
//Specify specific data types for generic interfaces when creating classes.
class Mouse implements USB<String>{
    @Override
    public String show() {
        return null;
    }
}

6.2 generic methods

The definition of a generic method has nothing to do with whether its class is generic or not. The class can be generic or not

Format of generic method:

public < generic ID > generic ID} method name () {}
 

Topics: WPF linq p2p