jdk1.5 new Features (iii) _ Generics

Source: Internet
Author: User

1, the description
Generics are provided to the Javac compiler, you can limit the input type in the collection, let the compiler block the source of the illegal input, the probability of the error from the runtime to the compile time, which makes it easier to find the program error, so that our program more secure.

• Type parameterization vs. original type compatibility:
A parameterized type can reference an object of the original type, and the compiler does not report an error, such as:
collection<string> C = new Vector ();
The original type can reference an object of a parameterized type, and the compiler does not report an error, such as:
Collection C1 = new vector<string> ();
• Parameterized types do not take into account the inheritance relationships of type parameters, and the compiler reports errors such as:
Vector<string> v = new vector<object> ();
vector<object> v1 = new vector<string> ();
• When creating an array instance, the elements of the array cannot use parameterized types, and the compiler reports an error, such as:
vector<integer> v2[] = new vector<integer>[10];

2, in the generic type. Wildcard characters
Because the parameterized type does not take into account the inheritance relationship of the type parameter, we can use the. Wildcard characters, using the. Wildcard characters can refer to other such parameterized types. A variable that is defined by a wildcard character is used primarily as a reference. You can call methods that are not parameterized, and you cannot invoke methods related to parameterization.
Example:
public static void Printcollection (Collection<?> Collection) {
Collection.add ("abc"); Error, because you add a string value to the collection, and collection is not necessarily a string
Collection.size (); Calling a method that is not parameterized
}

3, in the generic type. Extension of wildcard characters
• Limit the upper bounds of the wildcard character:
vector<?  Extends number> x = new vector<integer> (); That's right
vector<?   Extends number> x = new vector<string> (); Error
• Limit the bottom bounds of the wildcard character:
vector<?  Super integer> x = new vector<number> (); That's right
vector<?    Super integer> x = new vector<byte> (); Error
• Tips
Qualifying wildcard characters always include themselves
• sample
Hashmap<string, integer> maps = new hashmap<string, integer> ();
Maps.put ("Zc", 20);
Maps.put ("GBB", 30);

set<map.entry<string, integer>> entryset = Maps.entryset ();
For (entry<string, integer> entry:entryset) {
System.out.println (Entry.getkey () + ":" + entry.getvalue ());;
}

4, the definition of generic methods
Example:
public static <T> void swap (T a[],int i,int j) {
T temp = a[i];
A[i] = A[j];
A[J] = temp;
}

Call:
Swap (new string[]{"abc", "XYZ", "ZC"}, 1, 2); That's right
Swap (new int[]{1,2,3,4},2,3); Error, only reference type can be used as the actual parameter of a generic method

Description
• The angle brackets used to place the type parameters of a generic should appear after other modifiers of the method and before the return type of the method. Typically, type parameters are represented in uppercase letters of a single letter.
• Only reference types can be used as actual parameters for generic methods
• You can use the extends qualifier when defining generics, and you can specify multiple boundaries using &.
• Generics can be used in common methods, construction methods, and static methods.
• You can also use a type variable to represent an exception, called a parameterized exception, that can be used in a throws list of methods and not in a catch clause. Such as:
private static <t extends Exception> SayHello () throws T {
try {
catch (Exception e) {//cannot use T
Throw (T) E
}
}
• You can have multiple type parameters in a generic type, separated by commas: for example:
Public <K,V> GetValue (K key) {...}

5. Define generic type
1, if you want to use the same generic parameter in many places in the instance object of the class, that is, if the generic type that you are referencing has to remain the same actual type, it is defined by the generic type, that is, the class-level generics, the syntax is as follows:
public class Genericdao<e> {
public void Add (E obj) {};
Public E-GetByID (int id) {return null;};
}

2. Class-level generics are parameterized type variables based on the type information specified when the class name is referenced, such as:
Genericdao<string> DAO = null;
New Genericdao<string> ();

3. Note
• When you parameterize a generic type, the instance of the type parameter must be a reference type and cannot be a basic type.
• When a variable is declared as a generic, it can only be called by instance variables and methods (and inline types), not by static variables and static methods. Because static members are shared by all parameterized classes, static members should not have class-level type parameters.  such as: public static void Add (E obj) {}; This is wrong.

6. Obtain the actual type parameters of the generic type by reflection
Import Java.lang.reflect.Method;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import Java.util.Date;
Import Java.util.Vector;

public class Generictest {

public static void Main (string[] args) {
try {
Method method = GenericTest.class.getMethod ("Applyvector", Vector.class);
type[] types = Method.getgenericparametertypes ();
Parameterizedtype ptype = (parameterizedtype) types[0];
Get the original type class Java.util.Vector
System.out.println (Ptype.getrawtype ());
Get the actual parameter type class Java.util.Date
System.out.println (ptype.getactualtypearguments () [0]);
catch (Exception ex) {
Ex.printstacktrace ();
}
}

public static void Applyvector (Vector<date> v) {

}
}

Note: This is the principle that many frameworks implement automatic conversion 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.