Detailed Generic Stack

generic

what is generic

Generics is a concept used in programming languages ​​that allows one or more type parameters to be used when defining a class, interface or method. By using generics, you can write generic code that works on different types of data, improving code reusability and type safety.

The benefits of generics

1. Type safety: By using generics, type errors can be caught at compile time instead of errors at runtime.
2. Code reuse: Common code can be written and shared between different types, reducing redundant code writing.
3. Performance optimization: Since the generic code is type-safe, the compiler can optimize for a specific type to improve the performance of the code.

For example, in Java, you can use generics to define a general-purpose List container, and specify the type of elements to be stored when instantiating the List. This allows the same List class to be used in different scenarios without creating a separate container class for each data type. This approach increases code flexibility and reusability.

generic stack

What is a generic stack

A generic stack is a data structure implemented using the concept of generics, which can store elements of different types. In a generic stack, you can specify the type parameter to define the type of element to be stored, and perform common operations on the stack, such as push and pop.

Generic stack definitions typically use classes or interfaces, and use angle brackets (<>) to specify type parameters.

Benefits of Generic Stacks

1. Avoid type conversion errors: By using generics, you can avoid the problem of frequent type conversions when using the stack. The generic stack will perform type checking at compile time to ensure that only elements of the specified type can be stored, thereby improving the type safety of the code.
2. Improve the readability and maintainability of the code: the generic stack can store and operate different types of data, making the code more general and readable. There is no need to create different stack classes for each data type, reducing redundant code writing and improving code maintainability.
3. Code reuse: By defining a generic stack, you can use the same stack to implement logic in different scenarios without reimplementing the stack for each type. This reduces duplication of code and improves code reusability and scalability.
4. Performance optimization: Since the generic stack determines the type to be stored at compile time, the compiler can optimize the code when generating machine code. This can lead to more efficient runtime performance, since runtime type checking and conversions are no longer required.
5. Restrictions on data types: By using generics, the data types stored in the stack can be restricted. This means that only elements of the specified type can be stored, providing stricter data constraints and reducing potential errors and exceptions.

Overall, generic stacks provide more flexible, type-safe, and reusable data structures that simplify code implementation and improve code readability, maintainability, and performance.

Code

Suppose we have an array, and we need to continuously realize the push and pop operation, so the push sequence is 1,2; the pop is 2,1;
Picture: array push
First, we define an array and give it an initial value:

    public static int[] data = new int[5];

We need a pointer-like variable to determine the last position of the array:

public static int size = 0;

Then we write to the stack method:

  public void push(int i){
    
    
        data[size ++] = i;
        if (size == data.length){
    
    
            data = Arrays.copyOf(data,data.length * 2);
        }
    }

Suppose we pass in a 1, then i = 1. size = 0, because it is size++, so the order is data[0] = 1, size+1 = 1. When the size is equal to the length of the array, if I continue to push the stack, it will cause the array to go out of bounds and need to be expanded.

Next is the pop method:

    public int pop(){
    
    
        if(size == 0){
    
    
            throw new RuntimeException("栈为空")}
        int old = data[size-1];
        size = size - 1;
        return old;

    }

It should be noted that size represents the next coordinate to be pushed onto the stack, so size has no elements, and size-1 represents the element to be pushed onto the stack.
The full code is:

public class DemoStack {
    
    

    public static int[] data = new int[5];

    public static int size = 0;

    /**
     * 
     * @param i
     */
    public void push(int i){
    
    
        data[size ++] = i;
        if (size == data.length){
    
    
            data = Arrays.copyOf(data,data.length * 2);
        }
    }

    public int pop(){
    
    
        if(size == 0){
    
    
            throw new RuntimeException("栈为空");
        }
        int old = data[size-1];
        size = size - 1;
        return old;

    }


}

The generic stack means that what I want to push into the stack is not only the int type of the above code, but also other types. So we just need to change int to E

public class EDemoStack<E> {
    
    

    public  Object[] data = new Object[5];

    public  int size = 0;

    /**
     *
     * @param i
     */
    public void push(E i){
    
    
        data[size ++] =  i;
        if (size == data.length){
    
    
            data = Arrays.copyOf(data,data.length * 2);
        }
    }

    public E pop(){
    
    
        if(size == 0){
    
    
            throw new RuntimeException("栈为空");
        }
        E old = (E) data[size-1];
        size = size - 1;
        return old;

    }
    
}

With this, our code is complete. Let's run a test on the code:

public static void main(String[] args) {
    
    
        EDemoStack<String> stack = new EDemoStack<>();
        stack.push("123");
        stack.push("喜羊羊");
        stack.push("aaa");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }

Output result:
insert image description here

Guess you like

Origin blog.csdn.net/cang_ling/article/details/131845206