Starting with the concept of generics in JDK1.5, generics are essentially a type that enables programmers to define security. In the absence of generics, Java also provides a reference to the object "arbitrary" operation, which is the object reference "down" and "Move Up" operations, but some forced type conversion errors may not be caught by the compiler, and after running an exception, There are security implications for forced type conversions to be seen.
1. Defining generics
A generic mechanism appears after JDK1.5, with the following syntax:
Class name <T>
where T represents the name of a type.
The examples are as follows:
Public classOverclass<t> { PrivateT over; PublicT Getover () {returnOver ; } Public voidSetover (T over) { This. over =Over ; } Public Static voidMain (string[] args) {//instantiate an object of type BooleanOverclass<boolean> Over1 =NewOverclass<boolean>(); //instantiate an object of type floatOverclass<float> Over2 =NewOverclass<float>(); Over1.setover (true);//No type conversions are requiredOver2.setover (12.3f);//No type conversions are requiredBoolean B =Over1.getover (); Float F=Over2.getover (); System.out.println (b); System.out.println (f); }}
As you can see from the program above, a class that uses a generic definition can specify <T> true types according to different requirements when declaring the class object, whereas a type conversion operation is no longer required when a method in a class is used to pass or return a data type, but instead is used when declaring a generic class object <> The data type set in the symbol.
Using generics in this form will not cause a classcastexception exception, because you can check whether the type match is correct in the compiler.
When defining a generic class, the type name is typically expressed using T, and the element of the container is expressed using E.
2. General usage of generics
2.1 Declaring multiple types when defining a generic class
When defining a generic class, you can declare multiple types with the following syntax:
Mutioverclass<t1,t2>
where mutioverclass represents the generic class name, T1 and T2 are the types that may be defined.
This allows you to specify multiple types when instantiating an object of the specified type, for example:
mutioverclass<boolean,float> m=New mutioverclass<boolean,float>;
2.2 Declaring an array type when defining a generic class
You can also declare an array type when you define a generic class. Examples are as follows:
Public classArrayclass<t> { Privatet[] Array; Publict[] Gett () {returnArray; } Public voidsett (t[] array) { This. Array =Array; } Public Static voidMain (string[] args) {Arrayclass<String> A =NewArrayclass<string>(); String[] Array= {"member 1", "Member 2", "Member 3", "Member 4", "Member 5" }; A.sett (array);//call the Set () method for(inti = 0; I < A.gett (). length; i++) {System.out.println (A.gett () [i]);//Call the Gett () method to return the value in the array } }}
The results are as follows:
You can declare an array using generics, but you cannot use generics to create an instance of an array. The use of the error is as follows:
Public class Arrayclass<t> {//private t[] array=new t[10];//can not use generics to create an instance of an array }
3. The collection class declares the elements of the container
You can use the K and V two characters to represent the key values in the container and the specific values corresponding to the key-value pairs. As shown in the following example:
Public classMutioverclass<k, v> { PublicMap<k, v> m =NewHashmap<k, v> ();//Defining a collection HashMap instance//set the Put () method to deposit the corresponding key and key names in the collection object PublicV get (k k) {returnM.get (k); } Public voidput (k K, v V) {m.put (k, v); } Public Static voidMain (string[] args) {//instantiating a generic class objectMutioverclass<integer, string> mu =NewMutioverclass<integer, string>(); for(inti = 0; I < 5; i++) { //puts the key name and the specific value into the collection based on the length of the collectionMu.put (i, "I am a member of the collection:" +i); } for(inti = 0; I < mu.m.size (); i++) { //call the Get method to get the value in the collectionSystem.out.println (Mu.get (i)); } }}
In fact, the above definition of the set of generic classes in the collection framework has been generalized, can be used directly.
4. High-level usage of generics
Advanced usage of generics includes restricting generic types available and using type wildcard characters.
4.1 Restricting generic available types
You can use any type to instantiate a generic class object by default, but Java also restricts the type of the generic class instance to the following syntax:
extends anyclass>
Where Anyclass refers to an interface or class.
After you use a generic restriction, the type of the generic class must be an interface or class that implements or inherits Anyclass. Whether the Anyclass is an interface or a class, you must use the extends keyword when you make a generic restriction. Examples are shown below:
Public classLimitclass<textendsList> { Public Static voidMain (string[] args) {//classes that already implement the list interface can be instantiatedlimitclass<arraylist> L1 =NewLimitclass<arraylist>(); Limitclass<LinkedList> L2 =NewLimitclass<linkedlist>(); //This is wrong, because HashMap does not implement the list () interface//limitclass }}
4.2 Using a type wildcard character
A type wildcard is provided in a generic mechanism whose primary purpose is to restrict the type of the generic class from implementing or inheriting a subclass of an interface or class when creating a generic class object. To declare an object that can use the "?" Wildcard characters, while still using the extends keyword to restrict generics.
The syntax for using generic type wildcard characters is as follows:
extends List> a=null;
Among them, <? extends List> indicates that the type is unknown and can be instantiated separately when the generic object needs to be used.
As shown below:
extends List> a=null; a=new a<arraylist>(); a=new a<linkedlist> ();
If you instantiate a generic object that does not implement the list interface, the compiler will make an error.
In addition to instantiating an instance of a restricted generic type, you can also place the instance in the parameters of the method. As shown below:
Public void extends list>) {}
In the above code, the definition method effectively restricts the parameter type of the descendant DoSomething () method.
If you instantiate a generic class object in this form of a<?>, the default means that a can be specified as a subclass type that can instantiate object and the following. As shown below:
list<string> l1=New arraylist<string>(); L1.add ("member"); List<?> l2=L1; List<?> l3=new linkedlist<integer> ();
Generic type restrictions can be restricted in addition to downward limits, as long as the Super keyword is used when defining. For example, "A<? Super list> A=null; After this is defined, object a accepts only the List interface or the upper-level parent class type, such as "
A=new a<object> (); "
4.3 Inheriting generic classes and implementing generic interfaces
Classes and interfaces that are defined as generics can also be inherited and implemented. As shown below:
Public class Extendclass<t1> {}classextends extendclass<t1> {}
If you preserve the generic type of the parent class when inheriting the Extendclass class in the subclass class, you need to indicate it on inheritance, and if you do not specify it, use the extends extendclass<t1> statement to inherit the operation directly. The T1,t2 and T3 in the subclass class automatically become object, so the generic type of the parent class is generally preserved.
The defined generic interface can also be implemented as follows:
interface i<t1> {}classimplements i<t1> {}
5. Generic Usage Summary
A generic type parameter can only be a class type, not a simple type, such as a generic definition such as a<int> is wrong.
The number of types of generics can be multiple.
You can use the extends keyword to restrict the type of a generic type.
You can use wildcards to restrict the type of a generic type.
Java Generics overview