The use and understanding of generics in Java

Source: Internet
Author: User
Tags uppercase letter java se

What is a generic type?

Generics are a feature of programming languages. Allows programmers to write experience generics in strongly-typed programming languages
The code defines some variable parts that must be specified before use. The various programming languages and their compilers and operating environments have different support for generics. Parameterization of the type to achieve code reuse a data type that improves the productivity of software development. A generic class is a reference type, a heap object, and the concept of a type parameter is introduced primarily.

Defined:

Generics are a new feature of Java SE 1.5, and the nature of generics is a parameterized type, meaning that the data type being manipulated is specified as a parameter. This parameter type can be used in classes, interfaces, and methods
are called generic classes, generic interfaces, and generic methods, respectively. The benefits of introducing generics into the Java language are simple and secure.
In the case of Java SE 1.5, without generics, by referencing the type object to implement the "arbitrariness" of the parameter, the disadvantage of "arbitrariness" is to make an explicit coercion type
Conversion, which requires the developer to be able to predict the actual parameter type. The compiler may not prompt for errors in the case of coercion of type conversions, at run time
is an exception, which is a security risk.
Benefits of Generics:

The benefit of generics is that it checks for type safety at compile time, and all casts are automatic and implicit, increasing the rate of reuse of the code.

1. A generic type parameter can only be a class type (including a custom class) and cannot be a simple type.

2, the same generic can correspond to multiple versions (because the parameter type is indeterminate), different versions of the generic class instances are incompatible.

3, generic type parameters can have more than one.

4. Parameter types of generics can use extends statements, such as <t extends Superclass>. It is customary to call it "bounded type".

5. The parameter type of a generic type can also be a wildcard type. For example class<?> ClassType = Class.forName ("java.lang.String");

Attention:

    • Generics are a new feature of Java 1.5, which is referenced by C + + templates and is essentially an application of parameterized types (parameterized type).
    • Type parameters can only be used to represent reference types, generics require in Java, generics must be wrapped type, must be of type object, or a custom class, cannot pass in basic types such as int, double, char, and so on. , you must pass the wrapper type As Integer cannot be used to represent the base type, but passing the base type does not cause an error because they are automatically boxed into the corresponding wrapper class.
Use:
1 /*IG is equivalent to a placeholder, which is used to pass data types, not data values, called type parameters (names can be customized, and, of course, we have to follow the specifications)2  * 3 */4 //custom generic classes, where multiple generics can be separated by commas such as <ig,it,.. >5 classmyarrays<ig>{//The generic type of the class must be placed after the class name6     //position of the elements of the swap array7      Public voidRever (ig[] a) {8 System.out.println (a);9     }Ten } One  Public classCustomtoolclass { A    Public Static voidMain (string[] args) { -String[] Str=NewString[10]; -integer[] Intarr =NewInteger[10]; the       //The basic data type cannot be passed, even if it is an array of shapes, such as int[], it also has to pass int's wrapper class integer -       int[] arr =New int[10]; -      //myarrays<int> my1 = new myarray<int> ();//cannot be a basic data type -Myarrays<integer> My2 =NewMyarrays<integer> ();//can only be a wrapper class +       //My2.rever (arr); //cannot be a shaped array -       //The standard format is this, and the types on both sides match +myarrays<string> AA =NewMyarrays<string>(); A aa.rever (str); at       //The following two are also possible, but not recommended, this is Java in order to backward compatibility with the previous version of the design -myarrays<string> cc =Newmyarrays (); -Myarrays DD =NewMyarrays<string>(); -       //-------------------------------------------------------------- -Myarrays<integer> Aa1 =NewMyarrays<integer>(); - Aa1.rever (intarr); in   } -}

Compared to the definition of the normal class, the above code has more <iG> after the class name, IG is a custom identifier, is also a parameter, the type used to pass the data, not the value of the data, which we call the type parameter . In generics, not only can the value of the data be passed through parameters, but the type of the data can also be passed by parameter. IG is just a placeholder for the data type, and the runtime is replaced with the true data type.

The pass-through parameters (which we typically refer to) are surrounded by parentheses, such as (int x, double y), type parameters (generic parameters) surrounded by angle brackets, and multiple parameters separated by commas, such as <T> or <t, e>. Note: This is just a specification, and the name can be customized.

Type parameters need to be given after the class name. Once the type parameter is given, it can be used in the class. The type parameter must be a valid identifier, habitually using a single uppercase letter, typically K for the key, V for the value, E for an exception or error, and T for the data type in general sense.

A generic class must specify a specific type when instantiated, that is, to pass a value to the type parameter, in the form:
ClassName variable<datatype1, datatype2> = new Classname<datatype1, datatype2> ();
You can also omit the data type to the right of the equals sign, but you will get a warning that:
ClassName variable<datatype1, datatype2> = new ClassName ();

Because specifying a data type when using a generic class, assigning values to other types throws an exception, without the need for a downward transformation or a potential risk, is more practical than the automatic boxing and upward transformation described at the beginning of this article.

Test:

The use and understanding of generics in Java

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.