15-08
Use generics in custom classes, that is, generic classes.
Class worker {
}
Class student {
}
Class tool {
Private object OBJ;
Public void setobject (Object OBJ ){
This. OBJ = OBJ;
}
Public worker GetObject (){
Return OBJ;
}
}
// When can I define a generic class?
When the referenced data type to be operated in the class is unknown
In the early stage, objects were defined to complete expansion.
Now define generic Extension
The appearance of generics should be avoided.
Compile the error
Class utils <QQ> {
Private qq q;
Publi void setobject (qq q ){
This. q = Q;
}
Public QQ GetObject (){
Return Q;
}
}
Class genericdemo3 {
Public static void main (string [] ARGs ){
Tool T = new tool ();
T. setobject (new worker ());
T. GetObject ();
Utils <worker> U = new utils <worker> ();
}
}
15-09 generic Method
Class demo <t> {
Public void show (t ){
Sop ("show:" + t );
}
}
// The generic type defined by the generic class is valid throughout the class. If this method is used,
// The object of the generic class must be operated.
Class demo {
Public <t> void show (t ){
Sop ("show:" + t );
}
Public <t> void print (Q ){
Sop ("Print:" + t );
}
}
Class genericdemo {
Public static void main (string [] ARGs ){
Demo <integer> d = new demo <integer> ();
D. Show (New INTEGER (4 ));
D. Show (9 );
D. Show ("fdfdffd"); // failed. To operate the string, you must redefine it.
Demo <string> B = new demo <string> ();
B. Show ("dddd ");
B. Show (5); // failed.
// ______________ use the generic method
demo d = new demo ();
D. show ("dfdffd");
D. show (New INTEGER (4);
D. print ("FFD ");
}< br>
15-10 static method generics
15-11 interface
15-12 advanced generic usage
class genericdemo6 {
Public static void main (string [] ARGs) {
arraylist Al = new arraylist ();
Al. add ("FDFD");
arraylist All = new arraylist ();
All. add (4);
All. add (7);
All. add (1);
}
Public static void print (arraylist <string> Al ){
Integer <string> it = Al. iterator ();
While (it. hasnext ()){
Sop (it. Next ());
}
}
// This method can only use string, but cannot use integer. What should I do?
What about ?? Please use? Placeholder
Public static void print (arraylist <?> Al ){
Integer <?> It = Al. iterator ();
While (it. hasnext ()){
Sop (it. Next ());
}
}
Method 2
Public static <t> void print (arraylist <t> Al ){
Integer <t> it = Al. iterator ();
While (it. hasnext ()){
T = it. Next (); // This operation can be performed .....
// Sop (it. Next (). Length (); // at this time? Unavailable
Sop (it. Next ());
}
}
Generic limitation, missed
? Wildcard character: it can also be understood as a placeholder.
Limits on Generics
? Extends E: can receive E type or child Type
? Super E: can receive the parent type of E or E