Use and understanding of generics

Posted by cape on Sat, 26 Feb 2022 02:36:14 +0100

1. What makes generics?
2. Why use generics?
3. How to use generic [class, interface, method]
4. Limitations of generics.

What makes generics?

 1. Generic: when a class is defined, it does not set the data type for the attribute and method [return value, parameter] in the class. When you create an object of this class, you specify the corresponding data type for it.

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 shaped.

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

(3) The values of 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.

package com.am.demo01;

/**
 * @program: java Advanced generic
 * @description:
 * @author: Amu
 * @create: 2021-12-20 14:22
 **/
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. 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;
    }
}

Solve the security problem of data type consistency. Use generics.

Generic format:

public class name < T, E... > {/ / T, E are generic flags.
public T attribute name;
    public T getXXX(){}
    public void setXXX(T t){}
}

package com.am.demo02;

/**
 * @program: java Advanced generic
 * @description:
 * @author: Amu
 * @create: 2021-12-20 14:22
 **/
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;
    }
}

 

wildcard

In development, reference passing of = = object = = is the most common, but in the operation of generic class, when reference passing = = generic type must match = = before it can be passed, otherwise it cannot be passed.

package com.am.demo03;

/**
 * @program: java Advanced generic
 * @description:
 * @author: Amu
 * @create: 2021-12-20 14:48
 **/
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);
    }
}

 

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] class name < generic ID extends class > {}

[set lower limit]
Declaration object: class name <? Super class > object name;
Definition class: [access] class name < generic ID super class > {}

package com.am.demo04;

import java.util.Collections;

/**
 * @program: java Advanced generic
 * @description:
 * @author: Amu
 * @create: 2021-12-20 15:01
 **/
public class Test04 {
    public static void main(String[] args) {
        Info<Integer> a=new Info<>(25);//Create a generic Integer object for info
        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 upper generic limit for the parameter.
    public static void fun1(Info<? extends Number> a){
         a.show();
    }
    //The lower limit of generics is set. Must be String or a parent 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);
    }
}

 

Topics: Java C# TypeScript