One: generic class
Define generics on a class: scope is internal to the entire class
Format: public class class name < generic type 1,... >
Note: The generic type must be a reference type
Importjava.util.Arrays; Public classGenericclassdemo { Public Static voidMain (string[] args) {myarraylist<String> list =NewMyarraylist<string>(); List.add ("Javase"); List.add ("Java EE"); List.add ("Javame"); System.out.println (List.get (0));//JavaseSYSTEM.OUT.PRINTLN (list);//[Javase, Java EE, Javame] }}/*generic classes define generics on a class: scope is the internal format of the entire class: public class class name < generic type 1,... > Note: Generic types must be reference types*/classMyarraylist<t>{ Privateobject[] Elementdata =NewObject[10]; Public BooleanAdd (T e) {//iterates over the element values in the array, if the current element is NULL, indicating that there is no value at the current position, you can place the value in the element position for(inti=0; i<elementdata.length; i++){ if(elementdata[i]==NULL) {Elementdata[i]=e; return true; } } return false; } PublicT Get (intindex) { //determine if the index is correct if(index<0 | | index>elementdata.length-1){ return NULL; } return(T) Elementdata[index]; } //[Javase, Java EE, Javame]@Override PublicString toString () {StringBuilder sb=NewStringBuilder (); Sb.append ("["); for(inti=0; i<elementdata.length; i++){ //add elements that are not equal to null into SBObject value =Elementdata[i]; if(NULL!=value) {Sb.append (Value+","); } } //Remove the "," at the far right of the last element .String result = sb.tostring (). substring (0, Sb.length ()-1); returnresult+ "]"; }}
Output Result:
Javase
[Javase,javaee,javame]
Generic methods
Define generics on a method: scope is the whole method
Format: Public < generic type > return type method Name (generic type.)
Packagecn.edu360; Public classGenericmethoddemo { Public Static voidMain (string[] args) {Object obj= "Haha"; //Turn obj strong into string//string s = (string) obj;String s =cast (obj); System.out.println (s);//hahaobj= 123;//automatically boxed 123 into integers//Turn obj strong into an integer//integer i = (integer) obj;Integer i =cast (obj); System.out.println (i);//123 } /*generic methods define generics on methods: scope is the entire method format: public < generic type > return type method Name (generic type.) */ Public Static<T>T cast (Object obj) {return(T) obj;//What type do you want, I will give you a strong turn into what type }}
Output Result:
Ha ha
123
Interface generics can be passed along, and subclasses of an interface can also define their own generic type, in addition to generics.
Generic interface
To define generics on an interface
Format: public interface interface name < generic type 1...>
Public Interface Intertest<t> { void Test (T T);}
Public class Implements Intertest<e> { publicstaticvoid main (string[] args) { } @Override Public void Test (E t) { // TODO auto-generated method stub }}
Two,? , a type wildcard character
1. unqualified wildcard characters,<?>.
2. Upper bound wildcard character , <? Extends Number>. Indicates that the parameter type can only be a subclass of number.
3. lower bound wildcard,<? Supper number>. Indicates that the parameter type can only be a parent of number.
Importjava.util.ArrayList;Importjava.util.Collection;ImportJava.util.Iterator;//generics feature: The left and right types of generics must be consistent and must be reference types Public classGenericdemo { Public Static voidMain (string[] args) {/*Generic wildcard <?> any type, if not explicit, is object and any Java class.*/ //test1 (); /*? extends e down qualification, E and its subclasses*/ //test2 (); /*? Super e up-limit, E and its parent class*/test3 (); } /*Generic wildcard <?> any type, if not explicit, is object and any Java class.*/ Private Static voidtest1 () {Object obj= "Haha"; //collection<object> C = new arraylist<string> ();//Errorcollection<object> C =NewArraylist<object>(); Collection<?> C2 =NewArraylist<object>(); Collection<?> C3 =NewArraylist<animal>(); Iterator<?> iterator =C3.iterator (); //You cannot add a value to the C3 because you do not know what generic collection the C3 receives//you can take the value out and receive it with the object type, because whatever type of value is a subclass of objectobj =Iterator.next (); } /*? extends e down qualification, E and its subclasses*/ Private Static voidtest2 () {Collection<?extendsanimal> C =NewArraylist<animal>(); Collection<?extendsanimal> C2 =NewArraylist<pig>(); Collection<?extendsanimal> C3 =NewArraylist<dog>(); //collection< extends animal> C4 = new arraylist<object> (); //You cannot add a value to the C3 because you do not know what generic collection the C3 receives.iterator<?extendsAnimal> iterator =C3.iterator (); //The type of the value can be animal to receive, because the value added in the collection must be a value of the type of animal itself or subclassAnimal Animal =Iterator.next (); } /*? Super e up-limit, E and its parent class*/ Private Static voidtest3 () {//collection< super animal> C = new arraylist<pig> ();collection<?Superanimal> C2 =NewArraylist<animal>(); Collection<?Superanimal> C3 =NewArraylist<object>(); //You can add a value because the type of the generic is at least animal itself or the parent generic of the animal, and you can add at least the value of the animal type, depending on the characteristics of the polymorphismC3.add (NewAnimal ()); Iterator<?SuperAnimal> iterator =C3.iterator (); //because the largest parent class cannot be determined, only the Obj class can be used to receiveObject obj =Iterator.next (); } }classanimal{}classDogextendsanimal{}classPigextendsanimal{}
Benefits of Generics:
When you define how a generic object is used, you do not know what type T is, it may be of type String, or it may be an Integer type. If you define T as a deterministic generic data type, the parameter can only be that data type. At this point, a wildcard is used instead of a generic data type that is determined.
use generics, wildcards to improve code reusability.
divide an object into declarations and use two parts. Generics focus on code reuse on type declarations, and wildcard characters focus on code reuse on the use. Generics are used to define uncertainties for internal data types, and wildcard characters are used to define the object type uncertainties used.
Java generic Declaration and use of wildcard characters