Java generics explained in detail

Table of contents

Java Generic Concepts

Key features include

Advantages of Java Generics

example


Java Generic Concepts

Java generics is a mechanism for type checking and type inference at compile time, which allows us to write more general and reusable code, improves the readability and maintainability of the code, and ensures type safety.

The core idea of ​​​​Java generics is type parameterization, that is, type parameters are used to replace specific types in the definition of classes, interfaces or methods. These type parameters are replaced by specific types during instantiation, thereby achieving universality and type safety. .

Key features include

  1. Type parameters: Use type parameters in the definition of a class, interface, or method in place of a concrete type. For example, E in List<E> is a type parameter.
  2. Type erasure: Java generics implement type safety checks at compile time, but at runtime, the information of the generic type is erased and converted to the original type. This is to maintain compatibility with earlier versions of Java while reducing runtime overhead. For example, List<String> is erased to List at runtime.
  3. Upper and lower bounds: Use wildcards (?) to specify upper or lower bounds on generic types, thereby limiting the range of available types. For example, <? extends Number> indicates that only Number and its subclass types can be used.
  4. Generic classes and generic interfaces: Use type parameters in the definition of a class or interface to achieve generality of the class or interface. For example, List<E> is a generic class and Comparable<T> is a generic interface.
  5. Generic method: Use type parameters in the definition of the method to achieve the generality of the method. For example, Collections.sort(List<T>) is a generic method.

Advantages of Java Generics

Can improve the readability and reusability of the code, while ensuring type safety. It can check type errors at compile time, avoiding problems such as type conversion exceptions at runtime. However, due to the type erasure mechanism of Java generics, there will be some restrictions, such as the inability to use basic types as type parameters, and the inability to obtain the specific types of generic types. Therefore, there are some details and limitations to be aware of when using Java generics.

example

A Pair class is defined, which has two type parameters T and U, representing the types of the first element and the second element, respectively. The Pair class has a constructor that can be used to create a Pair object and provides methods for getting and setting elements.

public class Pair<T, U> {
    private T first;
    private U second;

    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public U getSecond() {
        return second;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public void setSecond(U second) {
        this.second = second;
    }

    public static <T> Pair<T, T> createPair(T first, T second) {
        return new Pair<T, T>(first, second);
    }

    public static <T extends Comparable<T>> T max(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        T max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i].compareTo(max) > 0) {
                max = array[i];
            }
        }
        return max;
    }
}

Guess you like

Origin blog.csdn.net/m0_67906358/article/details/130221569