Java Fundamentals: Generics and their erasure, non-covariance

Source: Internet
Author: User

Reprint Please specify the Source:Jiq ' s technical Blog

1 Generic Syntax:

Generic class: Class classname<t>{}

Generic method: Public <T> void F (T x) {}

Basic guidelines: If you use a generic method to replace the entire class with generics, you should use a generic method, because it can make things clearer.

2 Why use generics?

Before Java SE1.5, without generics, by referencing the type object to implement the "arbitrary" of the arguments, the disadvantage of "arbitrariness" is to make explicit coercion of type conversions, which require the developer to be able to predict the actual parameter type. In the case of coercion of type conversion errors, the compiler may not prompt for an error and an exception occurs at run time, which is a security risk.

The benefits of generics are:

(1) Check type safety at compile time ;

(2) and all conversions are automatic and implicit, increasing the rate of reuse of code .

One of the most compelling reasons for the emergence of generics is to create container classes.

Prioritize generic!!!

Using generics is more secure and easier than using types that need to be converted in client-side code.

When designing new types, make sure that they do not require this conversion to work. This usually means that the class is made generic.

Like what


When using a stack with client code, if you do not use generics, you also need to make unsafe type judgments, type conversions, and so on when you take objects from a stack, and the code is more complex. With a generic stack, there is no need for a type conversion in client code, and it is straightforward and not complex.

3 Generic array:

Unable to create a generic array, the general solution is to use ArrayList wherever you want to use a generic array.

Public <T> voidtest () {        //cannotcreate a generic array of tt[]tlist = new t[10];int[]ilist = new INT[10];//usea Rraylist<t>arraylist<t>slist = new arraylist<t> ();}

4 type erase:

First, the concept

Type erase: removes the type parameter information from the generic type, maps to only one copy of the bytecode, and, if necessary, type checking and type conversion.

The type of a generic type is erased at compile time by two steps:

1. Replace all generic parameters with their leftmost boundary (the top-most parent type) type.

2. Remove all the type parameters.

Note: Erasing is also why generics must be compiled for type checking because run-time type information is erased.

Second, erase example

(1) Container generic type erase:

ARRAYLIST<INTEGER>L1 = new arraylist<integer> (); arraylist<string> l2= new arraylist<string> (); Linkedlist<integer>l3 = new linkedlist<integer> (); List<string> L4 =new linkedlist<string> (); System.out.println (L1.getclass (). GetName ()); System.out.println (L2.getclass (). GetName ()); System.out.println (L3.getclass (). GetName ()); System.out.println (L4.getclass (). GetName ()); Outputjava.util.ArrayListjava.util.ArrayListjava.util.LinkedListjava.util.LinkedList
you can see that the type information of the above four generic types is erased, such as the bytecode generated by Arraylist<integer> and arraylist<string> after compilation is a copy.

(2) Custom generic type erasure:

Then look at a custom generic class:

Class Tobject<t>{privatet Obj;publicvoid Set (T object) {this.obj= object; System.out.println ("T:" +object.getclass (). GetName ());}        }
after the compilation is erased, the resulting class is this:

Class Tobject{privateobject Obj;publicvoid Set (Object object) {this.obj= object;}        }
The generic parameter T is first replaced by the top-level parent of the object, and then the type parameter T is removed.

(3) Custom inheritance relationship generic type erase:

Class Manipulator<textends superclass>{   private T obj;  Public manipulator (T x) {    obj = x;  }  public void DoSomething () {    obj.f ();   System.out.println (Obj.getclass (). GetName ());}  }
First replace the generic parameter T with the upper boundary, and then remove the generic parameter:

Class manipulator{   private superclass obj;  Public manipulator (superclass x) {    obj = x;  }  public void DoSomething () {    obj.f ();   System.out.println (Obj.getclass (). GetName ());}  }

third, the reason for erasure:

Generics are not at the beginning of Java, erasing is a compromise of generic implementations in Java .

Specifically, there are two reasons why generic code requires a type wipe:

(1) The introduction of generic code can not affect the existing code class library, so the generic code needs to be erased as non-generic code;

(2) When generic code is used as a class library, for compatibility, you do not need to know whether generic code uses generics, so it needs to be erased;

5 non-covariant:

(1) Arrays and generics comparison

Arrays are covariant and generics are non-covariant.

What is covariance? As an example:

An array covariant (covariant) refers to the base class of sub[] If the class base is the base class of a class sub.

Generic immutable (invariant) means that list<base> is not a base class for list<sub>.

(2) Why non-covariant generics

The generic compile-time type checking (type-safe) attribute determines that it is non-covariant.

Arraylist<object> objlist = new arraylist<long> ();

Can ' t compile Pass

Type Safety Check

object[] Objarray = new LONG[10];

Compile OK

If the Arraylist<long> type object can be assigned to a arraylist<object> type reference, then the principle of generic type safety is violated.

Because if you do this, the compiler will result in a non-long object that can be placed in a previous container. But the array doesn't matter, he's not type-safe.

Look at the following code, the first line of compilation error is because it is not covariant, then why the second row can?

list<type> Listt = new arraylist<subtype> ();

Can ' t compile Pass

list<? Extends type> Listt = new arraylist<subtype> ();

Ok

Refer to generic wildcard, which is the function

Non-covariant does not mean that you cannot use subclasses in the generic code where the parent class appears, as the following code is legal:

arraylist<type> list = new arraylist<type> ();

Type is superclass

List.add (New subtype ());

Subtype is subclass

type[] tt = new TYPE[3];

Tt[0] = new subtype ();

(3) The problems caused by the array can be covariant:

The covariance of arrays can cause some errors, such as the following code:

public static Voidmain (string[] args) {     object[] array = new STRING[10];      Array[0] = ten;  }     
it is possible to compile the pass because the array is covariant, and a reference to the object[] type can point to an object of type string[]. However, the following exceptions will be reported when running:

Exception in thread "main" Java.lang.ArrayStoreException:java.lang.Integer

However, this is not the case for generics:

public static Voidmain (string[] args) {      list< object> List = newarraylist< string> ();      List.add (10);  
This code does not even compile.

6 wildcard characters:

The role of wildcards in the type system is derived from the feature that does not occur with covariant (covariant). That is, the wildcard is partly due to a breakthrough in the non-covariant limit .

It can be considered that the wildcard character makes list<?> the base class of list<anytype>, List< Extends type> is the base class for list<subtype>.

Collection1 can store any type Collection<?>collection1 = new arraylist<string> (); collection1 = newarraylist< Integer> (); collection1 = newarraylist<object> (); Collection3 means that it can hold a subclass of number or number  collection<?extends number> collection3 = Null;collection3 = Newarraylist<number> (); collection3 = Newarraylist<double> (); collection3 = newarraylist<long> (); Collection4 means that it can hold an integer or integer parent class  collection<? superinteger> collection4 = Null;collection4 = Newarraylist<object> ();

Java Fundamentals: Generics and their erasure, non-covariance

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.