“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Those of you who study Java are familiar with generics, and we often deal with them in our daily work. We can say that generics is both familiar and unfamiliar, familiar is that we will write and use it every day, but really let us go into the analysis, to explain the use of generics, we are difficult to explain clearly, this article will take you to understand generics in the most easy to understand way, to analyze generics.

An explanation of generics

Generics: Generics are the standards and specifications, or features, of a programming language.

Generics in general: Generics are basically what we parameterize types, like when we’re defining a List, we can say List

so that we can define the type that the List stores during the coding phase. This way, we can use generics to regulate and constrain the values in our collection when we operate on the List. If we pass in illegal types, the program will find the problem for us at compile time and there will be no hidden exceptions.

In the following example, if we were not constrained by generics, we would write code and run code without knowing it would fail, and we would only throw an exception if the program executed to this point.

List list = new ArrayList(); list.add("abc"); list.add(100); for(int i = 0; i< list.size(); I++) {System. Out. Println (" execution to the first "+ (I + 1) +" loops." ); String str = (String) list.get(i); System.out.println(str); }Copy the code

Execution Result:

Execute to the first loop. ABC executes through the second loop. Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at com.zhj.business.test.Test01.main(Test01.java:18)Copy the code

Result analysis: it can be seen that the program completed the first loop completely, and only triggered the type conversion exception in the second loop. When the project is large, details like this are easy to overlook, so we use generics to constrain the type so that we can extract the data and save it to the corresponding type, without having to force it, so there are no appeals.

Properties of generics

When the result of generics is properly verified during compilation, information about generics is erased, and methods for type checking and casting are added at the boundary between the object entering and leaving the method.

Generic information does not enter the runtime phase.

Conclusion: Generics are logically seen as different types, but are actually the same basic type.

Usage of generics

Generics can be used in three ways:

  • A generic class

    Public class Result<T> implements Serializable {/** ** private Integer code; /** * private String MSG; /** * return data */ private T data; public Result(Integer code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; }}Copy the code
  • A generic interface

    List is the most typical generic interface

    public interface List<E> extends Collection<E> {
    ​
    }    
    Copy the code
  • Generic method

    The toArray() method in the List interface is a typical generic method

    * @param T[] the generic argument * @return T[] returns the type T[] * * 2) Only methods that declare <T> are generic, and member methods that use generics in a generic class are not generic. * 3) <T> indicates that the method will use the generic type T before you can use the generic type T in the method. * 4) Like the definition of generic classes, here T can be written as any identifier, common parameters such as T, E, K, V are often used to represent generics. */ public <T> T[] toArray(T[] a) {int size = size(); */ public <T> T[] toArray(T[] a) {int size = size(); if (a.length < size) return Arrays.copyOf(this.a, size,(Class<? extends T[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }Copy the code

Note:

  • The type parameters of a generic type can only be class types, not simple types.

  • You cannot use the Instanceof operation on an exact generic type.

  • When implementing a generic interface, if no generic argument is passed, the declaration of the generic type must be added to the class when declaring the class. Otherwise, an error will be reported, as shown in the following example

    public interface List extends Collection

  • If a static method uses generics, the parameters of the generic type cannot be accessed, and the static method must be defined as a generic method

    public static void show(T t)

  • Generics can specify a boundary

    on a generic method that the boundary must be added between the permission declaration and the return value

  • In a generic method, you can also specify multiple generics <T,K> between permission declarations and return values.

  • The type wildcard is usually used with? Instead of the concrete type argument List<? > wildcard > replaces arguments like String.

Flexible use of generics can greatly enhance the quality of the program, people can actively use.