“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”


Tips: This article is about 2419 words, read about 2-3 minutes, hope you can read patiently, if you are already familiar with the knowledge points, you can directly through the directory to jump to place of interest to you, hope you read this article can help you, if you have any good Suggestions and views in the process of reading, welcome to leave a message at the bottom of the article or direct messages, I to you opinion Thank you again for reading this article.

One: generic knowledge points

Two: What are generics

Generics, a new feature in JDK1.5, is a syntactic sugar used to solve the problem of indeterminacy of object types.

Extended knowledge: Syntactic Sugar, also known as sugar-coated grammar, is a tactic added to a computer language that has no effect on the language’s functionality but is intended to make it more efficient for programmers to develop it. In plain English, syntactic sugar is a wrapper around existing syntax.

Common grammatical sugar:

  1. Generics and type erasure
  2. Automatic packing and unpacking, variable length parameters
  3. Enhanced for loop
  4. Inner class and enumeration class

Generics can be used in classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.

One: Generic classes (classes with one or more type variables)

// K,V represents a generic type. The specific type is not known when compiling, but needs to be specified when instantiating
public genericClass<K,V> xxxx
Copy the code

Two: Generic interfaces (interfaces with one or more type variables)

// K,V indicates a generic type
public interface genericInterface<K> xxx
Copy the code

Generic methods (methods with one or more type variables)

// K,V represents a generic type. The type is not known at compile time, and the type needs to be specified when calling the method
public <T> void genericMethod(T,V)
Copy the code

4. Why do generic methods need to add a generic type before the return value type, otherwise it will report an error?

A: This is the Java way of declaring generic methods. It defines the number of generic identifiers that the method has before the return value declaration.

Three: What are the benefits of using generics

Before JDK1.5, if we did not know the corresponding type, we could use the Object type as a placeholder, but there was a problem later: casting was required, and there could be type errors.

1. Security: Type check will be performed at compile time, and errors will be reported if the type is not correct. In addition, the casting of generic types is automatic and implicit, avoiding possible ClassCastException errors during casting.

2. Improve code reuse: Generic casts are automatic and implicit.

3. Improve readability.

Four: How to use generics

(a) the purpose of the generic type is to solve the problem of how to define the parameter type when the object type is uncertain, so, when the parameter type is not determined, you can use the wildcard of the generic type for placeholder.

T, K, V,? We can use random letters from A to Z to replace them. However, the use of wildcard numbers can improve the readability, and their specific meanings are as follows:

  1. “?” Usually represents an indeterminate Java type
  2. “T” represents a specific Java type
  3. “K” stands for Key in the Java Key value
  4. “V” stands for Value in Java key values
  5. “E” stands for Element.

(3) Common wildcard types

1, no boundary wildcard:
indicates that there are no restrictions, and unbounded wildcards indicate that generics are in use. If not specified, no values can be added.

2, upper bound bound wildcard, such as
; The extends keyword means that the parameters in this generic type must be E or a subclass of E.

3. Lower wildcards, such as
; The super keyword indicates that the parameters in this generic type must be of the specified type E, or a parent of the type, up to Object.

Five: The underlying implementation of generics

(a) the generic type is in the compile time for type check, if the type check does not pass, the compiler will report an error, it is implemented through the compiler.

(2) Type erasure: The generics check is only performed at the compile stage. The bytecode generated by the compilation does not contain the type parameters in the generics. This is called generic erasure, as shown in the following example:

List<Apple> list1 = new ArrayList<>();
List<Fruit> list2 = new ArrayList<>();
// The result is true
System.out.println(list1.getClass() == list2.getClass());
Copy the code

Six: Limitations of generics

  1. When specifying generic types, primitive types cannot be used, only their wrapper types can be specified, as in: Person”<“double”>”, because generics are essentially OBEjCT types, reference types, not primitives (primitives are the eight basic types that store values on the stack, whereas reference types store the addresses of objects).

  2. Cannot instantiate a type variable directly, for example :new T(…) NewT, […]. Or tc lass.

Seven: Common generic interview questions

What are generics in Java?

A: Generics are a new feature in JDK1.5. It is just a syntactic sugar for solving the problem of class, interface, method, attribute object type uncertainty.

What are the benefits of using generics?

1. Type checking at compile time, added security (security)

2. Casts are both automatic and implicit, improving code reuse (simplicity)

3. Improved readability

How do Generics work in Java?

A: It is implemented by a compiler that does type checking during compilation

(4) What is type erasure?

There is only the notion that generics are converted at compile time to a concrete primitive type at run time, that is, the type is “erased” at run time.

Generics are only compiled, and the bytecodes generated by compilation do not contain the type parameters in the generics.

(5) what are qualified and unqualified wildcards in generics?

Qualified wildcards restrict types; A generic type must be initialized with a qualified type, otherwise a compilation error will result. On the other hand, it represents unqualified wildcards, because it can be replaced by any type.

Qualified wildcards: also divided into upper wildcards <? Extends E>, lower wildcard <? super E>

  1. Upper wildcard <? Extends E> means that a generic parameter must be of type E or a subclass of E

  2. The lower wildcard <? Super E> means that the generic parameter must be E or a superclass of E, up to type Object

Unqualified wildcard: The type is “< ‘T’ >” and can be replaced by any type. It indicates that there is no restriction and the generic parameter can be any qualified type.

List<‘T’> and List<? What is the difference between?

There are two usage scenarios for generics:

  1. Declare a generic class or method

  2. Use generic classes or generic methods

<‘T’> : The first usage scenario is: declare generic classes, methods, interfaces, the purpose of using type parameters is to solve the object type uncertainty. Such as:

public class ArrayList<T> extends AbstractList<T>{}
Copy the code

< ‘? “> < span style =” box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; white-space: inherit! Important;”

List<? > list =new ArrayList<Integer>();
Copy the code

(6): Do you understand generic wildcards and upper and lower bounds? Generic wildcards are divided into: qualified wildcards (upper bound wildcards
, lower wildcard
) and unqualified wildcards, which can be used as follows:

  1. The boundary wildcard <? Extends E> means that a generic parameter must be of type E or a subclass of E.

  2. The lower wildcard <? Super E> means that a generic parameter must be a parent of E or E, up to Object.

  3. Unqualified wildcards: Represented by A single T(or any a-Z letter), this indicates that there are no restrictions and that generic arguments can be of any qualified type.

Eight:

I believe that seeing here, you will have a deeper understanding of generics, learning a knowledge, only know the principle of this knowledge, will not feel half-informed.

Thank you for reading this article, and if you find something wrong with it, feel free to send a message or leave a comment below. If you think this article is of some help to you, please give me a like and attention, so that I have more motivation to bring more articles to you, thank you.