A simple generic example of Java generics

Source: Internet
Author: User

Transferred from https://my.oschina.net/fhd/blog/289945


Examples are as follows:

Package test;

public class Gen<t> {
private T ob;
Public
Gen (T o) {
ob = O;
Public
T Getob () {return
ob;
Public
void ShowType () {
System.out.println (' Type ' T is ' + ob.getclass (). GetName ());
}
}

Package test; public class Gendemo {public static void main (string[] args) {* * in Java7 and later versions, the generic type can be omitted from the constructor, as in the following
        In this way, * only a pair of angle brackets <> * *//gen<integer> IOB = new gen<> (88);
        gen<integer> IOB = new gen<integer> (88);
        Iob.showtype ();
        int v = Iob.getob ();
    System.out.println ("value:" + V); }
}

Let's analyze some of the code in the example above.

First, notice how this line of code declares the generic class Gen:

public class Gen<t> {...}

where T is the name of the type parameter. This name is a placeholder for the actual type, and when the object is created, the actual type is passed to Gen. So in Gen, T is used as long as the type parameter is required. Note that T is included in <>, as long as the type argument is declared, it needs to be specified in angle brackets. Because Gen uses type parameters, Gen is a generic class, also known as a parameterized type.

Next use T to declare object OB:

Private T ob;

As explained earlier, T is a placeholder for the actual type that will be specified when the Gen object is created. Therefore, OB is the actual type of object passed to T. For example, if you pass a string to T,ob, it will be a string type.

Now analyze Gen's constructor:

Public Gen (T o) {ob = O;}

Note the type of parameter O is T, which means that the actual type of O depends on the type passed to T when the Gen object is created. Also, because the parameters O and the member variable OB are of type T, they will have the same type when the Gen object is created.

You can also use type parameter T to specify the return type of the method, as in the Getob () method:

Public T Getob () {return OB;}

Because OB is also a T-type, the type of OB is compatible with the return type specified by the Getob () method.

The ShowType () method displays the type of T by calling the GetName () method on the Class object. This class object is returned by using the GetClass () method of the OB call. The GetClass () method is defined by the object type, so the method is a member of all classes. This method returns a class object that corresponds to the class to which the calling object belongs. class defines the GetName () method, which returns a string representation of the class name.

The Gendemo class demonstrates the generic gen class. It first creates an orthopedic version of the Gen class:

gen<integer> IOB = new gen<> (88);

Let's analyze the code carefully. First look at the Declarations section, note that the type integer is specified in the angle brackets behind the Gen. Therefore, the integer is the type parameter passed to Gen. This effectively creates a version of Gen. In this release, all references to T are converted to references to integers. So for this declaration, OB is the integer type, and the return type of the Getob () method is also integer.

Before continuing, it must be noted that the Java compiler does not actually create different versions of the Gen class, or that no other generic class is created. Although this is helpful, it is not the case. Instead, the compiler erases all generic type information, replacing it with a required type conversion, so that the code behaves as if it had created a specific version of the Gen class. Therefore, there is actually only one version of the Gen class in the program. The process of erasing generic type information is called: type erasure.

We then look at the Creation object section of the code above, noting that the type parameter integer was still specified when the Gen constructor was invoked. This is required because the type of the object to which the value will be assigned (here is IOB) is gen<integer>. Therefore, the reference returned by new must also be of the gen<integer> type. If not, a compilation error is generated. If in the Java7, you can omit the integer, leaving only a pair of bracket <>, and the omitted type can be inferred from the type inference of the variable. Because IOB is a gen<integer> type, you cannot reference objects of the gen<double> type, which is one of the main benefits of generics because it ensures type safety.


Generics use objects only

When you create an instance of a generic class, the type argument passed over must be a class. You cannot use basic types, such as int, char. For Gen, you can pass any class to T, but you cannot pass the base type to the type parameter T. Of course, the inability to use the base type is not a serious limitation because the type wrapper can be used to encapsulate the base type. The Java automatic boxing and unboxing mechanism makes the use of type wrappers transparent.


Generic types based on different types of parameters are different

References to specific versions of generic types and other versions of the same generic type are not type-compatible, which is a more critical point to understand about generic types. such as:gen<integer> and gen<double> are not type-compatible, although they are gen<t> types.

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.