[Learn JAVA from scratch | Article 26] Generic Supplementary Knowledge

Table of contents

Foreword:

More applications of generics:

Generic class:

Generic method:

Generic method:

Summarize:


Foreword:

In the previous article, we introduced the basics of generics, that is, generics are used when creating collections. At this time, generics are more of a constraint. In this article, we will introduce some more knowledge of generics, such as applying generics to classes, applying generics to methods, and applying generics behind interfaces.

More applications of generics:

Generic class:

Usage scenario: If in a class, the data type of a variable is uncertain, you can define a class with generics.

A generic class is a widely used concept in programming that allows us to use type parameters when defining a class to represent unknowns of a certain type. By using generic classes, we can write more flexible and reusable code because these classes can be applied to many different data types.

The definition of a generic class is similar to a normal class, except that a pair of angle brackets (<>) are added after the class name, which contains one or more type parameters. A type parameter can be a concrete class, interface, or abstract class that represents the data type actually passed to the generic class.

Here is a simple example of a generic class:

public class Box<T> {
    private T value;

    public void setValue(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

In the above example, the Box class is defined as a generic class with a type parameter T. This class has a member variable value whose type is T. The setValue method can accept any type of value and assign it to the value variable. The getValue method returns the value of value.

When using generic classes, we can specify concrete type parameters to create objects as follows:

Box<Integer> integerBox = new Box<>();
integerBox.setValue(10);
int value = integerBox.getValue();
System.out.println(value); // 输出:10

Box<String> stringBox = new Box<>();
stringBox.setValue("Hello");
String str = stringBox.getValue();
System.out.println(str); // 输出:Hello

In the above code, we created two Box objects, one of type Box<Integer> and the other of type Box<String>. By specifying a type parameter, we can determine the type of value at runtime and use the corresponding operation.

Generic classes can also be used with other generic classes or generic interfaces, providing greater flexibility and extensibility. They can be used in scenarios such as data structures (such as lists, stacks, queues, etc.), algorithm implementations, and various general tool classes.

To sum up, a generic class is a class with type parameters that allows us to handle different types of data in a generic way in code writing. By using generic classes, we can improve code reusability and flexibility, making code more concise, safe and readable.

Generic method:

A generic method is a way of using generics in programming, which allows us to use type parameters inside a method to represent unknowns of some type. By using generic methods, we can write more general and flexible code that can be applied to different types of data.

The definition of a generic method consists of two parts: the method signature and the type parameter declaration . In the method signature, we use a type parameter to indicate the unknown type, which is placed before the method's return type. A type parameter can be a concrete class, interface or abstract class.

Here's a simple example of a generic method:

public class Utils {
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }
}

In the above example, the printArray method is a generic method that takes a single type parameter T. This method accepts an array of type T and iterates over each element in the printed array.

When using a generic method, we can explicitly specify the type parameters when calling the method, or the compiler can perform type inference based on the parameter type. Examples are as follows:

Integer[] intArray = {1, 2, 3, 4, 5};
Utils.printArray(intArray); // 输出:1 2 3 4 5

String[] stringArray = {"Hello", "World"};
Utils.<String>printArray(stringArray); // 输出:Hello World

In the above code, we call the printArray method separately and pass different types of arrays as parameters. In the first example, the compiler deduces that T is of type Integer based on the parameter type; while in the second example, we explicitly specify that T is of type String.

Generic methods can also have multiple type parameters, and type wildcards can be used to limit the range of types, and type parameters can also be used in method parameters. They provide greater flexibility and can be applied in a variety of different scenarios.

In summary, a generic method is a way of using type parameters inside a method, which allows us to handle different types of data in a generic way. By using generic methods, we can increase the generality and flexibility of the code, make the code more reusable, and ensure type safety at compile time.

Generic method:

A generic interface is an interface in which type parameters are used in the interface definition to represent unknowns of a certain type. By using generic interfaces, we can define common interfaces that can be applied to different types of data, thereby increasing the reusability and flexibility of the code.

The definition of a generic interface is similar to a normal interface, except that a pair of angle brackets (<>) are added after the interface name, which contains one or more type parameters. A type parameter can be a concrete class, interface, or abstract class that represents the actual data type passed to the generic interface.

Here is a simple example of a generic interface:

public interface List<T> {
    void add(T element);

    T get(int index);
}

In the above example, the List interface is defined as a generic interface with a type parameter `T`. The interface declares two methods: the add method is used to add elements to the list, and the get method is used to obtain the element at the specified index position in the list.

When using a generic interface, we can specify specific type parameters in the class that implements the interface or where the interface is used. Examples are as follows:

public class ArrayList<T> implements List<T> {
    private T[] array;
    private int size;

    public ArrayList(int capacity) {
        array = (T[]) new Object[capacity];
        size = 0;
    }

    public void add(T element) {
        array[size] = element;
        size++;
    }

    public T get(int index) {
        return array[index];
    }
}

In the above code, the ArrayList class implements the List interface and specifies the type parameter T. Inside the class, we use a generic array array to store elements, the add method adds elements to the array, and the get method obtains the element at the specified index position.

The benefit of using a generic interface is that it makes the code more generic and flexible for different types of data. By specifying the type parameter in the implementation class or where it is used, we can determine the specific data type used at runtime.

Generic interfaces can also be used with other generic classes, generic interfaces, or generic methods as parameters or return types of methods, providing greater flexibility and scalability.

To summarize, a generic interface is an interface with type parameters that allows us to handle different types of data in a generic way. By using generic interfaces, we can improve the reusability and flexibility of the code, making the code more concise, safe and readable.

Summarize:

        We have introduced three common uses of generics in detail in this article: generic classes, generic methods, and generic interfaces. In fact, the role of generics here is a tentative data type . It makes the code more reusable and greatly improves the efficiency of the code. Therefore, we must use these three methods proficiently to better grasp the meaning of generics.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

 

 

Guess you like

Origin blog.csdn.net/fckbb/article/details/131463904