[Data Structure] First introduction to generics

Article directory


General classes and methods can only use specific types: either basic types or custom classes. This restriction will greatly restrict the code. So we introduced generics. Generics, as the name suggests, means broadly. It just works for many, many types. From a code perspective, the type is parameterized.

Let's look at the following code:

public class Demo03 {
    
    
    public static void main(String[] args) {
    
    
        MyArray myArray = new MyArray();
        myArray.setValue(0,10);
        myArray.setValue(1,"hello");
        String pos = myArray.getPos(0); //error
        System.out.println(pos);
    }
}

class MyArray {
    
    
    Object[] arr = new Object[10];

	//获取下标为pos的元素
    public Object getPos(int pos) {
    
    
        return this.arr[pos];
    }
	//在pos位置放入val元素
    public void setValue(int pos,Object val) {
    
    
        this.arr[pos] = val;
    }
}

Through the above code, we find that although in this case, any data in the current array can be stored, in more cases, we still hope that it can only hold one data type. Instead of holding so many types at the same time.

Generic syntax:

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

We can rewrite the above code using generics:

public class Demo03 {
    
    
    public static void main(String[] args) {
    
    
        MyArray<Integer> myArray = new MyArray<>();
        myArray.setValue(0,10);
        myArray.setValue(1,11);
    }
}

class MyArray<T> {
    
    
    T[] arr = (T[])new Object[10];

    public T getPos(int pos) {
    
    
        return this.arr[pos];
    }
    public void setValue(int pos,T val) {
    
    
        this.arr[pos] = val;
    }
}

Code explanation:
The angle brackets T after the class name represent placeholders, indicating that the current class is a generic class.
Arrays of generic types cannot be new, such as T[] t = new T[5];
add Integer after the type to specify the current type.
No forced type conversion is required.
The compiler will help us perform type checking when storing elements.

Use of generic classes

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

for example:

MyArray<Integer> list = new MyArray<Integer>();
//等价于 MyArray<Integer> list = new MyArray<>();

Note: Generics can only accept reference types, and all basic data types must use wrapper classes.
Upper bound of generics
When defining a generic class, sometimes it is necessary to impose certain constraints on the type variables passed in, which can be restricted through type boundaries.

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

for example:

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

This way it only accepts subtypes of Number as type arguments for E.

MyArray<Integer> str1; // 正常,因为 Integer 是 Number 的子类型
MyArray<String> str2; // 编译错误,因为 String 不是 Number 的子类型

Let's look at this exercise: write a generic and implement a method that finds the maximum value of an array of a specified type.

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        FindMaxValue<Integer> tFindMaxValue = new FindMaxValue<>();
        Integer[] array = {
    
    1,4,6,2,10};
        Integer max = tFindMaxValue.findMax(array);
        System.out.println(max);
    }
}

//泛型类
//<T extends Comparable<T>>  T一定是实现了Comparable接口
class FindMaxValue <T extends Comparable<T>> {
    
    
    public T findMax(T[] arr) {
    
    
        T max = arr[0];
        for (int i = 1; i < arr.length; i++) {
    
    
            if (max.compareTo(arr[i])<0){
    
    
                max = arr[i];
            }
        }
        return max;
    }
}

We can also write the above code using generic methods

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        Integer[] array1 = {
    
    1,4,6,2,10};
        Integer max1 = FindMaxValue1.findMax(array1);
        System.out.println(max1);
    }
}

class FindMaxValue1 {
    
    
    //泛型方法
    public static <T extends Comparable<T>> T findMax(T[] arr) {
    
    
        T max = arr[0];
        for (int i = 1; i < arr.length; i++) {
    
    
            if (max.compareTo(arr[i])<0){
    
    
                max = arr[i];
            }
        }
        return max;
    }
}

Guess you like

Origin blog.csdn.net/qq_58032742/article/details/132829825