1. Generic type
(1) Benefits of generics:
1, the original program to run when the problem may occur, the issue of conversion to compile time.
2, improve the safety of the program.
(2) Erase mechanism of generic type
Let the compiler block the insertion of illegal data into the collection at the source code level. But the compiler compiles a generic type of
Java program, the resulting class file will no longer have generic information. Simply put: Generics only work in the compile phase
Invalid run phase.
(3) Application of generic type
1. Declaring generics on a class
Class name <T> {}
Where can a generic declared on a class be applied?
Generics can be applied to instance properties, and instance methods.
Member of the class: member Property member method
Member Properties: Instance Attribute class properties
Member Methods: Instance method class methods
The generic type declared on a class cannot be applied to class properties, class methods, because class properties, class methods can be called directly through the class name, when generics do not have specific types. Class name. Attribute class name. method.
Generics can be applied to parameters and return values on a method.
public class genec<t>{
T T;
Public T Fun (t t1) {
}
}
2. Declaring generics on a method
What is the difference between declaring a generic and using a generic type?
Declare generic:<> when parentheses
Apply generics: Without parentheses
How do I declare generics on a method?
"Generic must be declared before the return value.
Public <T> void Fun1 (T T2) {
}
Java Fundamentals 4