Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - What is generics in java and how to use generics?
What is generics in java and how to use generics?
This is one of the questions you will be asked at the beginning of various Java generic interviews, mainly focusing on the primary and intermediate interviews:

1: What is generics?

generics are a wide range of types, and they are also a data type. This data type can be arbitrary, and the type cannot be determined during the writing process. When creating an object, you must specify a specific type, or you can do it without specifying it, but there will be some errors.

generics are compiler behaviors and can only be effective at compile time. If they can cross the compiler, generics are meaningless.

2. Generic class

How to define a generic class?

add <; > ,< > You can write any character of any length in, and it cannot be a numerical value. (generally represented by 26 uppercase English letters)

Generic class < Specific type > Variable name = new generic class <; > ();

3. How to use generics

There are the following usage scenarios and where to put them

Generics can only define reference data types, but cannot use basic data types

Generic classes, generic methods, generic interfaces and generic wildcards

For example, when acting on classes (public class animal <: E> { E pet; }), generics follow the class, and you can specify the type of pet inside the class with generics.

when acting on an object (animal <; Dog> str = new Animal< Dog> (); ), generics follow the class, so that the pet attribute of the object class is of type Dog.