What is generic?
First, we will write a simple generic class to illustrate:
[Java]
Public class Generics <T> {// T is short for type, which can be replaced by any name
Private T o; // generic member variable
Public Generics (T o ){
This. o = o;
}
Public T getObject (){
Return o;
}
Public void setObject (T o ){
This. o = o;
}
Public String getType (){
Return o. getClass (). getName ();
}
}
This generic class includes its own constructor, And the get, set, and getType methods.
We can use this class as follows:
[Java] www.2cto.com
Public class GenericsDemo {
Public static void main (String [] args ){
Generics <Integer> export bject = new Generics <Integer> (1 );
System. out. println ("the value of your bject is" + Your bject. getObject ());
System. out. println ("the type of your bject is" + Your bject. getType ());
Generics <String> stringObject = new Generics <String> ("hi, generics! ");
System. out. println ("the value of stringObjectis" + stringObject. getObject ());
System. out. println ("the type of stringObjectis" + stringObject. getType ());
}
}
We can use the versions of various types of this generic class (for example, Integer, String, and all Object classes and their subclasses ). However, generic data does not support basic data types.
Obviously, using java generics saves the need for forced type conversion. The compiler retains the type information of the parameter, performs the type check, and performs the type conversion operation. Therefore, developers do not need to ensure the security of type conversion, but leave this to the compiler.