data structure generics

1. Definition

Let us first see how the official definition of generics

Doesn't it look easy, explain:

That is, we want to have a data type that can be applied to various data types. From the code point of view, it is to realize the parameterization of the type.

2. References

Example: Implement a class that contains an array member, so that any type of data can be stored in the array, and the value of a subscript in the array can also be returned according to the member method.

Ideas :

We have seen integer arrays: int[ ] arr1 = {1,2,3}; character arrays String[ ] arr2 = {a,b,c}

Now we want to have an array like {1 , 2 , a , b , 3.432} Integer, character, floating point, etc.

We know that Object is the parent class of any class

So we write like this:

 public Object[] array = new Object[10];

Then we can do the following operations on this array

class MyArray{
    public Object[] array = new Object[10];
    public Object getPos(int pos){ //获取pos下标的值
        return array[pos];
    }
    public void setPos(int pos,Object val){ //给pos下标放一个元素
        array[pos] = val;
    }
}

So we call these two methods

But we can't get the element with subscript 1, because the data type in Array is Object, and ret is a string.

Object is the parent class of String, which is a downward transformation, so an error will be reported.

We need to force type conversion so that no error will be reported

String ret = (String) myArray.getPos(1);

 But we want to:

1. Can we specify the type ourselves?

2. Can we no longer perform mandatory type conversion

So generics appeared to meet our requirements.

3. Grammar

<T>: placeholder —> represents that the current class is a generic class

1. <Integer> specifies that the type used in the current class is the Integer type, that is, specifies that the array is of the Integer type
2. Generics do two things during compilation:
      2.1 When storing elements, type checks are performed
      2.2 When taking elements, the class

3. <> is a reference type

class MyArray<T>{ //定义一个泛型类
    //public Object array[] = new Object[10];
    //public T[] array = new Object[10]; 报错
    public T[] array = (T[]) new Object[10];
    public T getPos(int pos){ //获取pos下标的值
        return array[pos];
    }
    public void setPos(int pos,T val){ //给pos下标放一个元素
        array[pos] = val;
    }
}
public class TestDemo {
    public static void main(String[] args) {
       
        MyArray<Integer> myArray = new MyArray<Integer>();//也可以写成new MyArray<>()
        myArray.setPos(0,1);
        Integer ret = myArray.getPos(0);
        System.out.println(ret);

        MyArray<String> myArray1 = new MyArray<String>();
        myArray1.setPos(0,"abc");
        String ret1 = myArray1.getPos(0);
        System.out.println(ret1);
    }
}

Guess you like

Origin blog.csdn.net/benxiangsj/article/details/124520747