How to use Java generics?

In Java, generics are a mechanism that allows for checking and restricting data types at compile time. Using generics can improve code reusability and readability.

The basic usage of generics is as follows:

  1. Use angle brackets <> in the declaration of classes or methods to specify generic parameters. For example, declare a generic class:
public class Box<T> {
  private T content;
  
  public void setContent(T content) {
    this.content = content;
  }
  
  public T getContent() {
    return content;
  }
}
  1. When creating objects, you can specify a specific type as a generic parameter. For example, creating a Box object that stores integers:
Box<Integer> intBox = new Box<>();
intBox.setContent(123);
int num = intBox.getContent();
  1. Generic parameters in Java can be any valid Java type, including primitive types and reference types. For example, creating a Box object to store strings:
Box<String> strBox = new Box<>();
strBox.setContent("Hello");
String str = strBox.getContent();
  1. Generics can also be used for the return type and parameter type of a method. For example, defining a generic method:
public static <T> T getFirstElement(List<T> list) {
  if (list != null && list.size() > 0) {
    return list.get(0);
  } else {
    return null;
  }
}

In this way, the return value type can be determined based on the input parameter type.

The above is the basic usage of generics, there are more complex uses such as wildcards, upper and lower bounds, etc. Different uses are applicable to different scenarios, and the appropriate way of using generics can be chosen based on specific needs.

bannerAds