java--generics (the most understandable way to explain generics)

Source: Internet
Author: User

From:
Code Big Wet
Code Big Wet

Write in front:

As long as you carefully read, basic can be very familiar with the characteristics of generics. Generics occur after JDK1.5, such as ArrayList before JDK1.5, 2 questions appear

1: Add objects to ArrayList, add string and date, but we meant to add a string, the compiler would not check for errors and cause unpredictable errors.

The 2:get () method takes a forced type conversion when it gets an element.
So the introduction of generics is a good solution to these 2 problems.

  

  Note: Generics throw errors (exceptions) to the compile time.

1, generic class

A generic class is as follows;

Classpair<Te>{Private T first;private E second; public T getFirst () {return first;} public void setfirst (T first) {this.first = First } public E getSecond () {return second;} public void setsecond (E second) {this.second = Second } } 

T,e in angle brackets are called type variables.

2. Generic methods

Signature of a generic method:
public static T Getv (T T)
The type variable is followed by the method modifier, before the value is returned.

3. Type Erase

There is no generics in the JVM, that is, when the compiler is compiling, the type variable is erased and replaced by the bounding type. When the pair class above is compiled, the pair becomes this way:

 class pair{private    Span class= "hljs-built_in" >object first; private object second; public object GetFirst () { return first; } public void Setfirst (Object First) {this.first = First;} public object Getsecond () { return second; } public void setsecond (Object Second) {this.second = Second;}}         

The type variable is substituted for object. More types of substitution please continue reading;

Problem with type erase:
Define a sub-class of pair

class extendsPair extends Pair<Date,Date>{ public void setSecond(Date d){ super.setSecond(d); System.out.println("我是字类的方法"); }}
Pair pair=new extendsPair();        pair.setSecond(new Date());

The execution results are:
I'm the parent's method.
I am the method of the word class

Why would that be?

Because the subclass defines itself as apublic void setSecond(Date d)
But one way to inherit from the parent class is that public void setSecond(Object d) this is 2 different methods. When you point to an instance of a subclass with a reference to the parent class, and then call the Word method, the method that the compiler will only look for is the parent class, which is public void Setsecond (Object D). And the programmer's intention is to call the subclass's method public void setSecond(Date d) , so in this case, the compiler will generate a bridge method for us

public void setSecond(Object d){    setSecond((Date)d);}

So, as in the result, the Setsecond method of the parent class is called first, and then the Setsecond method of the subclass is called in this method.

4. Type qualifier

1. Type qualifier, using keyword extends to denote subtype qualification

For the following methods

public People getName(Pair<People,People> p){        return p.getFirst(); }

This method, we cannot pass in the Pair<Student,Studnet> parameter of the type, at this time we need to use the subtype qualification, this method is changed to:

public People getName(Pair<? extends People,? extends People> p){        return p.getFirst();    }

Use the keyword super to represent a super-type qualification, which <?> means no type qualification. For example a method Getpairs () We want to return to pair<>[]. There are no inheritance relationships among the elements of Pair<Student>,还有Pair<Scientist> student and scientist. It's only for<?>

2: Type-limiting considerations:

Look at the code below

public People getName(Pair<? extends People,? extends People> p){        Student student=new Student(); p.setFirst(student); return p.getFirst(); }

P.setfirst (Student) will error, because Pair< Extends people,? The Setfirst method of extends People> is

public void setFirst(<? extends People first) { this.first = first; }

The formal parameter is a subclass of people, but the compiler cannot determine whether student is a subclass of this subclass. However, for the Get method, the return type is always transformed into the people class. The Get () method will cause an error if the corresponding use of the super-type qualification.

5: Generic Considerations:
1:不能在泛型类的静态上下文中定义含有类型变量的静态成员,如:
class Pair<T,E>{ private static T name; ....

Just for generic classes, static methods can exist in the normal class above. The reason is very simple, such as Pair<String,String>和Pair<Date,Date> these 2 objects, then the two objects to share name, then the variable name is what type? There is a conflict.

2:泛型类不能继承异常类,也不能被抛出

Because generic classes cannot inherit Throwable, type variables can be thrown, such as:

public static <T extends Throwable> T get(T t) throws T{ return t; }
3:泛型数组是不合法的

You cannot create such an array:

Pair<String,String>[] pairs=new Pair<String,String>[10];

Because Paris is actually a pair[] type, we add elements of the date type that the compiler will not find. This creates an error that is difficult to locate. But we can define a generic array in the following way.

Pair<String,String>[] pairs=(Pair<String, String>[])(new Pair[10]); 
4:不能实例化类型变量

Cannot appear src as new T (), new t[]. Because after the type erase, T becomes boundingtype. Such an operation has no meaning.

Follow more good text:
Code Big Wet
Code Big Wet

Classification:JAVALabel:JAVA, generics

java--generics (the most understandable way to explain generics)

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.