The basic use of generics in Java

1. The introduction of generics

JDK1.5 after the introduction of generics.
If you need to define a coordinate classes described Point, necessary to provide two attributes x, y. For the content of these two properties may have the following options:

  1. x = 10, y = 20
  2. x = 10.1, y = 20.1
  3. x = 80 degrees east longitude, y = 20 degrees north latitude

Because the Point of x, y attribute in many types, so the use of Object to receive.
For example: define a class Point

//因为坐标可能是各种类型(Integer,Float,Double,String),
// 所以采用Object接收
public class Point1 {
    private Object x;
    private Object 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;
    }

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

    public static void main(String[] args) {
        Point1 intPoint = new Point1();
        intPoint.setX(20);
        intPoint.setY(10);     //10 ->Integer ->Object
        System.out.println(intPoint);

        Point1 strPoint = new Point1();
        strPoint.setX("东经120度"); //String - >Object
        strPoint.setY("北纬38度");
        System.out.println(strPoint);

        Point1 point1 = new Point1();
        point1.setX(120);
        point1.setY("北纬38度");
        System.out.println(point1);
    }
}
/**
Point1{x=20, y=10}
Point1{x=东经120度, y=北纬38度}
Point1{x=120, y=北纬38度}
*/

But for the last coordinate, set square to coordinate content settings become Integer and String type , but the receiver does not know, so there will be time to perform ClassCastException such as the following:

 //接收方
    Integer x = (Integer)point1.getX();
    Integer y = (Integer) point1.getY();

Or when parameter passing, you do not know what type, will be run when an exception occurs :

	public static int[] getXY(Point1 point1){
        Integer x = (Integer) point1.getX();
        Integer y = (Integer) point1.getY();
        return new int[]{x,y};
    }

to sum up:

  1. We hope that at compile time, detect the type mismatch, but the use of Object receives, it can not be found
  2. You must clearly know the specific type of reference data types Object parameter types
  3. Downward transition, the need instanceof Analyzing
    Example: For the above transmission parameters abnormality can be determined using instanceof
    public static int[] getXY(Point1 point1){
        Integer x = (Integer) point1.getX();
        if((point1.getY())instanceof Integer){
            Integer y = (Integer) point1.getY();
            return new int[]{x,y};
        }else {
            throw new ClassCastException("y 不是Integer类型");
        }
    }

2. The basic use of generics

  • It refers to a generic class definition at the time and does not set the class attributes and methods of the particular parameter type , but the class used when a loud noise is defined.

  • The basic syntax of a generic class:

     class  MyClass<T>{ 		
               	T value; 	
      }
    
  • Wherein < >the parameter T is the type referred to, used to refer to any type. Common are:

  • T represents any kind of general
  • E represents the Element of meaning, the meaning of abnormal or Exception
  • Key representatives of the meaning of K
  • Value V represents the meaning generally used in conjunction with the K
  • S represents the mean Subtype

2.1 generic class

If a class is < >defined, then it is called a generic class
Note : values received generic class, all the basic data types must use a package types
Example: use the generic class defined in Point

public class Point2<T> {
    private T x;
    private T y;

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

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

    public T getY() {
        return y;
    }

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

    public static void main(String[] args) {
        //JDK1.7后,泛型类型实例化对象构造方法<>不需要指定类型
        Point2<String> point = new Point2<>();
        point.setX("东经120度");    //此处setX中指定的是String类型
        point.setY("北纬38度");
        System.out.println(point);

        //当使用泛型类的时候,决定属性的具体类型
        Point2<Integer>point1 = new Point2<>();
        point1.setX(20);
        point1.setY(10);
        System.out.println(point1);

    }
}

In addition, when using a generic class, but also to avoid the downward transition, which means that security risks are eliminated up. After the introduction of generics, if explicitly set type, the type was set; if not set type. The default is Object.
Example: introducing a plurality of generic class parameters

public class Point3<T, E> {
    private T x;
    private E y;

    public T getX() {
        return x;
    }

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

    public E getY() {
        return y;
    }

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

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

    public static void main(String[] args) {
        Point3<Integer,String> p1 = new Point3<>();
        p1.setX(120);
        p1.setY("北纬38度");
        System.out.println(p1);

        Point3<Integer,Integer> p2 = new Point3<>();
        p2.setX(20);
        p2.setY(10);
        System.out.println(p2);
    }
}

2.2 generic method

Not only can be used to define the generic class, the method may also be defined separately.

Example: Using the generic method

public class Point4 {
	//只是针对方法中的参数,在方法的返回值前加上<T>
    public <T> void print(T t){
        System.out.println("泛型方法");
    }

    public static void main(String[] args) {
        Point4 point4 = new Point4();
        point4.print("hello");
        point4.print(new Point());
        point4.print(10);
    }
}

2.3 generic methods and generic class

Generic methods and generic classes may coexist .

Example: generic method and generic class coexist

public class Point5<T, E> {
    private T x;
    private E y;

    public T getX() {
        return x;
    }

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

    public E getY() {
        return y;
    }

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

    public <T> void print(T t){
        System.out.println("nonono");
    }

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

    public static void main(String[] args) {
        Point5<Integer,String> p5 = new Point5<>();
        p5.setX(120);
        p5.setY("北纬38度");
        System.out.println(p5);
        p5.print("hello");
    }
}

to sum up:

  • Generic classes and generic methods can coexist, both independently
  • Generic method has always been to own type parameter defined as the standard
  • To avoid confusion, if there is a generic method generic classes, the parameters of the two is best not to the same name

Guess you like

Origin blog.csdn.net/mi_zhi_lu/article/details/90680789