Java advanced Features-generic __java basics

Source: Internet
Author: User
Tags comparable

Generic Erase

Reflection mechanism

Custom generic Classes

Custom Type method

Java generic type related knowledge

1 Why generics are used

Resolves the security problems of element storage while solving the problem of the type strong turn when getting the collection elements.

Increase the reuse rate of your code.

For example, write a generic class, and we don't care about the specific type of the class, but instead use T to represent the type of change. T cannot represent the base data type.

Generics Note:

In expressions that use generics, if both sides use generics, the generics on both sides must be consistent.

If the expression has only one side that uses generics, then the other side of the expression may not use generics.

(If any type of data can be added to the collection, causing the collection type to be unsafe, the additional objects read may need to be converted, cumbersome and easy to appear)

Several concepts in generics:

Take ArrayList as an example,<> read typeof

E in ArrayList, called type parameter variable

The integer in ArrayList is called the actual type parameter

entire ArrayList generic type

The entire ArrayList is called a parameterized type Parameterizedtype.

ClassCastException (class conversion exception)

The following code:

ArrayList A1 = new ArrayList ();

A1.add (dog);

A1.add (CAT);

Dog temp = a1.get (0);

System.out.println (a1.get (0));

Dog temp = (Dog) a1.get (0);

Dog is an instance of the dog class

We first define a collection of ArrayList types and then add objects of dog type and cat type to the collection, which is completely permissible because all types of collections default to the object class, and there is no problem in the javac phase. However, in the Java phase (runtime), the exception of type conversions occurs, classcastexception.

Analysis:

1. When we put an object into the collection, the collection does not remember the type of the object, and when the object is fetched again from the collection, the object's compilation type is type Object and any Run-time type is of its own type.

2. If you want to use this object, you must make a cast.

"Excerpted from a blog"

Generics, JDK1.5, resolves data type security issues primarily by identifying the type of a property in a class or the return value and parameter type of a method in a class declaration. This allows you to specify the specific type you want as long as the class is declared or instantiated. 】

"Understanding of security risks":

Before java1.5, without generics, by reference to type object to achieve the "arbitrary" parameters, the arbitrary result is to do the display of the mandatory type conversion, but also requires the developer must be the actual parameter types foreseen, and for the forced type conversion errors, Javac does not show an error, it will be abnormal at run time, causing the JVM to crash. This is a security risk.

Reference Code Testgenerics.java

Generic class

Declaration of generic class:

Class/interface Name

Specifies the type of the generic method when you are using an object to tune a generic method. Public

<E> list<e> fromarraytolist (e[] e,list<e> List) {for

(E xx:e) {

list.add (xx);

} return

list;

}

list<integer> list3 = Order.fromarraytolist (in, List2);

Generics and Inheritance:

If class B is a subclass of Class A, then List < B > and list< a > have no inheritance relationship.

If you want to use inheritance in generics, you can use wildcard characters.

list< B > and list< a > are list<? Sub-Class of >

list<? Extends a> can store Class A and its subclasses.

list<? Super A> can store class A and its parent class

Use a collection of wildcard characters:

list<? > list: You can get the data from the collection list using wildcards, whose element type is object. The list in the collection of not-previously wildcard characters is added to the data except for NULL.

Generic Erase

We found that when using a generic class, though the different generic arguments were passed in, but there is no real sense of generating different types, the generic classes passed in different generic arguments have only one memory, that is, the original most basic type (what type of object is new and what type is it in memory), and of course, Logically we can understand several different generic types.

The reason is that the concept of generics in Java is proposed to causes it to only function in the code compilation phase, during compilation, for the correct validation of generic results, the generic information will be wiped out, that is, after the successful compilation of the class file does not contain any generic information. Generic information does not enter the Run-time phase.

To sum it up, a generic class is logically viewed as a number of different types, and is actually the same type. "Generics wipe Out"

The point in the Java Core Technology book:
There are no generic types of objects in the JVM, and all objects are normal objects. Whenever a generic type is defined, a corresponding original type is automatically provided (raw type), the name of the original type is the generic type name after the type parameter is deleted, the erased type variable, and the class qualification type is substituted.
Translation Generic expression:
Because of the generic erasure mechanism, the compiler translates the generic method to 2 virtual machine-specified
1 Invoking the original method
2 The data coercion type for the returned object type is converted to a generic type.
In summary, you need to remember the facts about Java generic conversions:
1, there is no generics in the virtual machine, only ordinary classes and methods
2, all type parameters are replaced by their qualified type
3, the bridge method is synthesized to maintain polymorphism
4, to maintain the security of the type, insert the coercion type conversion if necessary.

Reflection and Generics

Class classes are generic, and string.class are actually objects of class classes and unique objects.
The type parameter is useful because it allows the return type of the class method to be more targeted.

Generic type information in the JVM
The outstanding feature of Java generics is generic erasure, which can still get generic information through the reflection API.
The following methods:
public static < T extends comparable <? Supper t>> T min (t[] a)

The

can be obtained through the Reflection API:
After SE5.0, the new interface type, which contains subtypes under this interface:
Class: Description Specific type
Typevariable interface: Description type variable (textends comparable <? Supper t>)
Wildcardtype interface: Describes wildcard characters such as. Supper T)
Parameterizedtype Interface: Description generic class or interface type (comparable <? Supper t>)
Genericarraytype interface: Description generic array t[] a

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.