Java advanced programming basic self-study notes --- generic

This knowledge point is relatively simple!

 

 

Others turn to the collection for you to use, but you are not sure what type others use, you don't know what type to coerce into, you have to try one by one when you call, otherwise you have to ask, a lot.

basic concept:

As the name implies: a wide range of types. Usually, objects of the type can be stored in the collection. Essentially, all these objects are treated as Object types. Therefore, when the elements are taken out of the collection, they are also Object types. In order to express the most real data type of the element Need to force type conversion, and forced type conversion may cause type conversion exception;

In order to avoid the occurrence of the above errors, a generic mechanism has been proposed from jdk1.5, which is to use <data type> on the right side of the collection name to specify the type of elements that can be stored in the collection. If other types are placed, compilation errors will be reported. . Such as:

List lt1=new LinkeList();--When there is no generic type, you can store the personnel type object, and it will be troublesome to retrieve it (you need to force it, but I don’t know which one to force it, it’s easy to report errors)

List<String> lt1=new LinkeList<String>();-has the advantage of generics, that is, only String type can be placed, otherwise an error will be reported and the removal party (there is no need to force transfer)

Defect: This collection can only be placed in String or a subclass of String, (String has no subclass and is modified by fianl)

The type should be consistent before and after, keep the same, and write it down, this is a rule;

However, new features have been added since jdk1.7. The data type of the following <> can be omitted (remember not to omit the angle brackets), as follows:

Also known as diamond characteristics

 

The essence of generics is parameterized types. That is, let the data type be passed as a parameter. In the definition process of classes, interfaces, and methods, the data type to be operated on is specified by the passed parameter.

As long as the angle brackets are used, no matter what is inside, it is regarded as generic, but what does the E in <E> mean is that the formal parameter is responsible for the placeholder, and when using a collection, the data type in the <> is equivalent to the actual parameter responsible for the formal parameter Initialization, when the initialization is completed, all E is replaced with the type indicated by the actual parameter for use.

Such as:

Because the data types supported by Big E are very wide, all are called generics

Those classes with angle brackets <> support generics, and those without angle brackets do not support them. Please read the documentation.

Guess you like

Origin blog.csdn.net/bbs11007/article/details/107993862