Benefits of Java generics

Source: Internet
Author: User
Tags map class

JavaGeneric isJavaThe new feature of Se 1.5, the nature of generics is parameterized type, that is, the Data Type operated is specified as a parameter. This type of parameter can be used to create classes, interfaces, and methods, which are called generic classes, generic interfaces, and generic methods.

 

Generic (generic type or generics) is an extension of the Java type system to support the creation of classes that can be parameterized by type. You can regard the type parameter as a placeholder of the type specified when parameterized type is used, just as the method form parameter is a placeholder of the value passed during runtime.

You can see the motives of generics in the Collection framework. For example, the map class allows you to add any class objects to a map, even if the most common case is to save an object of a specific type (such as string) in a given map.
Because map. Get () is defined as the returned object, the results of map. Get () must be forcibly converted to the expected type, as shown in the followingCodeAs shown in:

Map M = new hashmap ();
M. Put ("key", "blarg ");
String S = (string) M. Get ("key ");

To makeProgramAfter compilation, you must forcibly convert the result type of get () to string and expect the result to be a string. However, it is possible that someone has saved something not a string in the ing. In this case, the above Code will throw classcastexception.
Ideally, you may come up with the idea that M is a map that maps the string key to the string value.This allows you to eliminate the forced type conversion in the Code and obtain an additional type check layer, which prevents someone from saving the wrong type keys or values in the set. This is what Generics do.

 

Benefits of generics

Introducing generics in Java is a major enhancement in functionality. Not only have the language, type system, and compiler greatly changed to support generics, but also the class libraries have been greatly revised. Therefore, many important classes, such as the collection framework, all of them have become generic.

This brings many benefits:

1. type security.The main objective of generics is to improve the type security of Java programs. By knowing the type limits of variables defined using generics, the compiler can validate the type assumptions to a much higher degree. Without generics, these assumptions exist only in the programmer's mind (or, if Lucky, in code comments ).

 

2. Eliminate forced type conversion.A secondary benefit of generics is thatSource code. This makes the code more readable and reduces the chance of errors.

 

3. Potential performance benefits.Generics are possible for greater optimization. In the initial implementation of generics, the compiler inserts forced type conversion (without generics, the programmer will specify these forced type conversion) into the generated bytecode. However, the fact that more types of information can be used in compilers makes it possible to optimize future JVM versions. Because of the implementation method of generics, it supports generics (almost) without JVM or class file changes. All work is done in the compiler. The Compiler generates code similar to the code written when there is no generic type (and forced type conversion), but it ensures type security better.

 

 

The advantage of introducing generics in Java is that it is secure and simple. The advantage of generics is to check the type security during compilation, and all the forced conversions are both automatic and implicit, improving the code reuse rate.

There are also some rules and restrictions for generic usage:
1. generic type parameters can only be class types (including custom classes), not simple types.
2. The same generic type can correspond to multiple versions (because the parameter type is uncertain), and the generic instances of different versions are incompatible.
3. There can be multiple generic type parameters.
4. You can use the extends statement for generic parameter types, for example, <t extends superclass>. It is a "bounded type ".
5. The generic parameter type can also be a wildcard type. For example, class <?> Classtype = Class. forname (Java. Lang. String );
There are many generic interfaces and methods. It takes some time to understand and use them skillfully. Here are two examples that I used to understand generics (based on my impressions) to implement the same function. One uses generics and the other is not used. Through comparison, you can quickly learn generic applications and learn about generic 70% content.

 

 

Previously, when we used collection classes such as arraylist in the previous article, we often forced type conversion after getting the object class to get the correct results. But now there may be a problem: we get a dog class, the program will not report errors after forced type conversion, but the type conversion error will occur during compilation. The generic type can solve this problem simply, direct value assignment without forced conversion:

Arraylist <bird> Al = new arraylist <bird> ();

Bird BD = new bird ("Xiaoxiao", 2 );

Al. Add (BD );

Bird temp = Al. Get (0 );

System. Out. println (temp. getname ());

Generics are also widely used. The most important role of generics is two aspects: simplicity and security, and improved code reuse rate. Generic refers to generic types, which are uncertain and can be considered as a template. You can use this form to modify the data type, there are three types: Generic method, generic class, and generic interface. See the following code:

Gen <string> Gen = new gen <string> ("huhua"); // create a generic object

GEN. showname ();

Class Gen <t> {

Private t o;

Public Gen (t o ){

This. O = O;

}

Public void showname (){

System. Out. println (O. getclass. getname ());

}

}

Only generic T is used to replace common data types such as string or Int. Other principles remain unchanged.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.