[Java] Simple use of generics


1. Packaging

Before understanding generics, we first understand what a wrapper class is. In Java, since the basic type does not inherit from Object, in order to support basic types in generic code, Java corresponds to a wrapper type for each basic type.

1. Basic data types and corresponding packaging classes

Basic data types Packaging
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

ExceptInteger and Character, the other basic types Package classes are all capitalized

2. Automatic boxing and automatic unboxing

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        Integer i = a;//自动装箱 把一个基本数据类型转变为包装类型
        System.out.println(i);

        Integer j = new Integer(20);
        int b = j;//自动拆箱 把一个包装类型转变为基本数据类型
        System.out.println(b);
    }
}

Insert image description here

3. Manual packing and manual unboxing

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        Integer i = Integer.valueOf(a);//手动装箱
        System.out.println(i);

        Integer j = new Integer(20);
        int b = j.intValue();//手动拆箱
        System.out.println(b);
    }
}

Insert image description here

2. What are generics

Generics are a new syntax introduced in JDK1.5. In layman's terms, generics: is applicable to many types. From a code perspective, the type is parameterized. The main purpose of generics: It is to specify the current container, what type of object it wants to hold, and let the compiler do the checking a>
Syntax:

class 泛型类名称<类型形参列表> {
    
    
// 这里可以使用类型参数
}
class ClassName<T1, T2, ..., Tn> {
    
    
}
class 泛型类名称<类型形参列表> extends 继承类/* 这里可以使用类型参数 */ {
    
    
// 这里可以使用类型参数
}
class ClassName<T1, T2, ..., Tn> extends ParentClass<T1> {
    
    
// 可以只使用部分类型参数
}

An example is shown below:

class MyArray<T> {
    
    
    public Object[] array = new Object[10];//1

    public void setValue(int pos,T val) {
    
    
        array[pos] = val;
    }
    public T getValue(int pos) {
    
    
        return(T)array[pos];
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        MyArray<Integer> myArray = new MyArray<>();//2
        myArray.setValue(0,10);
        myArray.setValue(1,20);
        myArray.setValue(2,30);
        int val = myArray.getValue(0);//3
        System.out.println(val);
        
        MyArray<String> myArray1 = new MyArray<>();
        myArray1.setValue(0,"hello");
        myArray1.setValue(1,"word");
        String ret = myArray1.getValue(0);
        System.out.println(ret);
    }
}    

Insert image description here
1. The < T > after the class name represents a placeholder, indicating that the current class is a generic class.
[Specification] Type parameters are generally represented by a capital letter. , commonly used names are:
E represents Element
K represents Key
V represents Value
N represents Number
T represents Type
S, U, V, etc. - the second, third, fourth type
2. Note 1, arrays of generic types cannot be new
3. Note 2, add < Integer > after the type to specify the current type
4. Note 3, no forced type conversion is required

3. Use of generics

grammar:

泛型类<类型实参> 变量名; // 定义一个泛型类引用
new 泛型类<类型实参>(构造方法实参); // 实例化一个泛型类对象

Examples are as follows:

MyArray<Integer> myArray = new MyArray<Integer>();//此处的类型实参可以省略

Note: Generics can only accept classes, and all basic data types must use wrapper classes

4. Raw Type

A naked type is a generic class without type parameters, as shown below:

MyArray myArray = new MyArray();

Note: We should not use naked types ourselves. Naked types are a mechanism reserved for compatibility with older versions of API

5. How are generics compiled?

Erase mechanism:
During the compilation process, the mechanism of replacing all T with Object is called: erasure mechanism
Java's generic mechanism is implemented at the compilation level. The bytecode generated by the compiler does not contain generic type information during runtime

6. Upper bound of generics

When defining a generic class, sometimes it is necessary to impose certain constraints on the type variables passed in. This can be done through type boundaries
Syntax:

class 泛型类名称<类型形参 extends 类型边界> {
    
    
...
}

Example:

public class MyArray<E extends Number> {
    
    
...
}

Only accepts subtypes of Number as type arguments of E
Complex example:

public class MyArray<E extends Comparable<E>> {
    
    
...
}

E must implement the Comparable interface

7. Generic methods

Definition syntax:

方法限定符 <类型形参列表> 返回值类型 方法名称(形参列表) {
    
     
... 
}

Example:

public class Util {
    
    
        //静态的泛型方法 需要在static后用<>声明泛型类型参数
        public static <E> void swap(E[] array, int i, int j) {
    
    
            E t = array[i];
            array[i] = array[j];
            array[j] = t;
        }
}

Summarize

1. Generics parameterize the data type and transfer it
2. Use < T > to indicate that the current class is a generic class.
3. The advantages of generics so far: data type parameterization, automatic type checking and conversion at compile time

Guess you like

Origin blog.csdn.net/2301_78373304/article/details/134696803