Java foundation "generic"

  What is a generic?

  Generic implementation of the concept of a parameterized type, so that the code can be applied to various types. The original purpose is to generic class or method can have the broadest expression. It is with the type of constraint between the decoupling is achieved by the use of a class or method.

  General classes and methods can only be used to represent a specific class members, or to write code that can be used with a variety of types, this approach will have a significant restraint on the code, the use of generics can be a good solution to this problem.

  Generics are simple to use:

    Before using generally generic class or interface name previously defined in the "<T>"; where "<>" is fixed grammar, '<....> "where there may be a plurality of types of generalization, the definition of the type general definition of capital letters.

    

  For Java container classes, use of generics is essential, because the container class storage elements can not be customized for a particular object or on a specific chain of inheritance, some people may say to Object storage can be achieved in different elements of storage. Object is used, but the use of Object storage, are "upward transition"; when you want to get a specific type, need to "downcast", this time of insecurity. Container is a collection of a certain type of memory, when the memory is fixed which type of data storage, storage with Object to do, no way to determine the type of memory storage type is not specified, will not be prompted.

  The use of generics can make the most widely used class of scenes, but also specify the specific type of class, which is its biggest advantage.

  Define multiple objects in a generic expression, called "tuples." It is the plurality of packaged objects in a single object. Maintaining a defined sequence of tuples of elements such as "<A, B, C>".

  Generic method:

  Generic used in the method. The first thing to note is that the base type is not the type of generalization as a parameter. The reason can, because after Java SE5 equipped with automatic packing and unpacking functions. Use the arrow can be used as method parameters and return values ​​to use, like the use of generic methods on which it resides is not a generic does not matter, that is to say the method can also define your own generic and use. Using generic methods can produce changes in the independent category, type of reason because if the method can not be diversified, so can only increase the expansion, this behavior is not a good solution, it is noteworthy problems, static methods can not access generic class generic parameters, static method to use generic parameters, must be referred to a generic method.

Behind the border issues with regard to generics update.

 

Guess you like

Origin www.cnblogs.com/liaobudao/p/11273014.html