1 List & lt Apple & gt Box = ...;
2 Apple Apple = box . get(0);
The above code itself is clear: box is a list containing Apple objects. The get method returns an instance of an Apple object without type conversion. If there is no generics, the above code needs to be written like this:
1 list box = ...;
2 Apple Apple =(Apple)box . get(0);
Obviously, the main advantage of generics is to let the compiler keep the type information of parameters and perform type checking and type conversion operations: the compiler guarantees the absolute correctness of these type conversions.
Instead of relying on programmers to memorize object types and perform type conversion-this will lead to the failure of the program at run time, which is difficult to debug and solve, and the compiler can help programmers to force a lot of type checking and find errors at compile time.
Composition of generics
The concept of type variables comes from the combination of generics. According to the Java language specification, a type variable is an unrestricted identifier, which is generated under the following circumstances:
Generic class declaration
Universal interface declaration
Generic method declaration
Generic constructor declaration
Generic classes and interfaces
A class or interface is generic if it has one or more type variables. Type variables are separated by angle brackets and placed after the class or interface name:
1 public interface list & ltT> extension set<T>{
2 ...
3 }
Simply put, type variables play the role of parameters and provide information for type checking for the compiler.
Many classes in the Java class library, such as the whole collection framework, have been generally modified. For example, the List interface we used in the first code above is a generic class. In code, box is a list.
In fact, this new generic tag, or the get method in this List interface, looks like this:
1t get(int index);
The get method actually returns an object of type T, which is in the list.
Generic methods and constructors
Similarly, methods and constructors can be genericized if they have one or more type variables declared on them.
1 public static & ltt>t get first(List & lt; T> list)
This method will accept a list.
example
You can use the generic classes provided in the Java class library or you can use your own generic classes.
Type safe write data ...
The following code is an example, and we create a list.
1 list & lt string & gtstr = new ArrayList & lt string & gt ();
2 str . add(" Hello ");
3 str.add ("the world." );
If we try to list
1 str . add( 1); //Unable to compile
Type safe reading data ...
When we use lists,
1 String myString = str . get(0);
traverse
Many classes in the class library, such as iterators.
1 for (iterator & lt string & gtiter = str.iterator (); ITER . has next(); ) {
2 String s = ITER . next();
3 system . out . print;
4 }
Use foreach
The "for each" syntax also benefits from generics. The previous code can be written like this:
1 for(String s:str){
2 system . out . print;
3 }
This is easy to read and maintain.
Automatic packing and unpacking.
When using Java generics, automatic boxing/automatic unboxing will be used automatically, just like the following code:
1 list & lt integer & gtints = new ArrayList & lt integer & gt ();
2 ints . add(0);
3 ints . add( 1);
four
5 int sum = 0;
6 for(int I:int){
7 sum+= I;
8 }
However, you have to understand that packaging and unpacking will bring performance loss, so GM should use it with caution.
Generics are a new feature of Java SE 1.5. The essence of generics is parameterized type, that is, the manipulated data type is specified as a parameter. This parameter type can be used to create classes, interfaces and methods, which are called generic classes, generic interfaces and generic methods respectively.
The advantages of introducing generics into the Java language are security and simplicity.
Before Java SE 1.5, parameters were "arbitrary" by referring to type objects without generics. The disadvantage of "arbitrary" is that it requires explicit forced type conversion, which requires developers to be predictable about the actual parameter types. In the case of forced type conversion error, the compiler may not prompt an error, and an exception will appear at runtime, which is a security risk.
The advantage of generics is to check the type safety at compile time, and all coercion is automatic and implicit, which improves the code reuse rate.
There are some rules and restrictions on using generics:
The type parameters of 1. generics can only be class types (including user-defined classes), not simple types.
2. The same generic can correspond to multiple versions (because the parameter types are uncertain), and different versions of generic class instances are incompatible.
3. Generic type parameters can be multiple.
4. For example, a generic parameter type can use the extends statement. Habitually become "bounded".
5. Generic parameter types can also be wildcard types. For example, class type = class.forname (java.lang.string);
Generics also have interfaces, methods, etc. There are many contents, and it takes some effort to understand and master them skillfully. The following are two examples I wrote when I was familiar with generics (written according to my impression), which realized the same function. One uses generics and the other doesn't. By comparison, I can quickly learn the application of generics and basically learn 70% of the contents of generics.
Example 1: generics are used.
Common class Gen¢T£.
Private mission; //Define generic member variables
Public Gender (Task)
this.ob = ob
}
public T getOb() {
Return ob;
}
public void setOb(T ob) {
this.ob = ob
}
public void showTyep() {
System. The actual type of out.println ("t") is "+ob.getClass ()". getName());
}
}
Public class GenDemo {
Public static void main(String[] args){
//Defines an integer version of the generic class gen..
Gen \u Integer \u intOb = new Gen \u Integer \u( 88);
intob . showtyep();
int I = intob . getob();
system . out . println(" value = "+I ");
system . out . println("-");
//Defines the string version of the generic class gen..
Gen ¢ String ¢ Strob = newgen ¢ String ¢ ("Hello Gen!" );
strb . showtyep();
string s = strb . getob();
system . out . println(" value = "+s);
}
Example 2: Generics are not used.
Public class Gen2 {
Private object ob; //Define common type members.
Common Gen2 (object ob) {
this.ob = ob
}
Public object getOb() {
Return ob;
}
public void setOb(Object ob) {
this.ob = ob
}
public void showTyep() {
System. The actual type of out.println ("t") is "+ob.getClass ()". getName());
}
}
Public class GenDemo2 {
Public static void main(String[] args) {
//Defines an integer version of the Gen2 class.
Gen2 intOb = new Gen2 (new integer (88));
intob . showtyep();
int I =(Integer)intob . getob();
system . out . println(" value = "+I ");
system . out . println("-");
//Defines the string version of the Gen2 class.
Gen2 strOb = new Gen2 ("Hello Gen!" );
strb . showtyep();
String s =(String)strob . getob();
system . out . println(" value = "+s);
}
}
Running results:
The results of running Demo in the two examples are the same, and the console output results are as follows:
The actual type of test is:
java.lang.Integer
Value = 88
-
The actual type of t is: java.lang.String
value= Hello Gen!
Process ends with exit code 0.
Knowing this, basic general application and code reading will not be a problem in the future.