当前位置:网站首页>Use and understanding of generics

Use and understanding of generics

2022-06-12 15:18:00 A_ M amu

1. What makes generics ?
2. Why use generics ?
3. How to use generics 【 class , Interface , On the way 】
4. Limitations of generics .

What makes generics ?

 1. Generic : Class is not defined as an attribute in the class , Method [ Return value , Parameters ] Set data type . When creating the object of this class, specify the corresponding data type .

Why use generics ?

  Example : Define a point class , attribute :x Coordinates and y coordinate .

requirement : x Coordinates and y The value of the coordinates .

(1) x Coordinates and y The values of the coordinates are all plastic .

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

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

reflection : x and y Type of attribute .Object. because Object Is the parent of all classes , Because of polymorphism .

package com.am.demo01;

/**
 * @program: java senior - Generic 
 * @description:
 * @author:  Amur 
 * @create: 2021-12-20 14:22
 **/
public class Test01 {
    public static void main(String[] args) {
        Point p1=new Point(15,25);// The values are all integers 
        Point p2=new Point(15.5,25.5);// Values are decimal 
        Point p3=new Point(" East longitude 150 degree "," North latitude 30 degree ");// Values are strings 

        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }
}
// reflection :  I can create one Point object , When the object is assigned x Coordinates are integers ,y The coordinates are string . Will this program report an error .【 Can't 】
//  Security issues that break the consistency of data types .
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 .

The format of generics :

public Class name <T,E....>{ //T,E Are generic flags .
    public T Property name ;
    public T getXXX(){}
    public void setXXX(T t){}
}

package com.am.demo02;

/**
 * @program: java senior - Generic 
 * @description:
 * @author:  Amur 
 * @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<>(" East longitude 150 degree "," North latitude 300 degree ");

         Point p4=new Point();// If no type is set for generics , The default is Object

        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }
}
//T: Used to T Represents a 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 == Object reference passing == Is the most common , But if in the operation of a generic class , When reference passing == Generic types must match == To deliver , Otherwise, it cannot be transmitted .

package com.am.demo03;

/**
 * @program: java senior - Generic 
 * @description:
 * @author:  Amur 
 * @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 also need to match .
           // reflection :  Can generics let him pass arbitrary types ?  Don't write   Or use wildcards .
    }
    public static void fun(Info<?> a){
         a.show();
    }
}

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

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

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

 

Restricted generics

stay == reference == in , In generic operations, you can also set the upper and lower range limits of a generic object . The upper limit of the range is used extends Keyword declaration , Indicates that the parameterized type may be the specified type or a subclass of this type , The lower range limit uses super Make a statement , Indicates that the parameterized type may be the specified type or the parent type of this type .

Format :  

[ Set the upper limit ]
Declare objects : Class name <? extends class > Object name ;
Defining classes :  [ Access right ] Class name < Generic identity extends class >{}

[ Set the lower limit ]
Declare objects : Class name <? super class > Object name ;
Defining classes :  [ Access right ] Class name < Generic identity super class >{}

package com.am.demo04;

import java.util.Collections;

/**
 * @program: java senior - Generic 
 * @description:
 * @author:  Amur 
 * @create: 2021-12-20 15:01
 **/
public class Test04 {
    public static void main(String[] args) {
        Info<Integer> a=new Info<>(25);// Create a generic as Integer Of info object 
        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);
    }
    // Set the Generic upper limit of the parameter .
    public static void fun1(Info<? extends Number> a){
         a.show();
    }
    // Set the lower limit of generics . It has to be for String or String Parent class of 
    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);
    }
}

 

原网站

版权声明
本文为[A_ M amu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010502355231.html