Java-Generic Learning
Generics are a new feature proposed by Java in JDK1.5, mainly for the security of Code and the re-use of code.
security : In the absence of a generic, it is primarily by passing an object to implement a reference to the incoming type, and then forcing the type conversion when the data is fetched, but there is a problem, such as a collection of a type of data, and then iterate through the collection of a type of data, A (a) object is required to cast, and if a data of type B is also stored in the collection, the problem is not reported during compilation and the runtime is problematic because it is not possible to convert data of type B to type a data, that is, types conversion exceptions. In order to solve this problem, the concept of generics is proposed. This allows you to qualify the B before it is stored in the collection, and eliminates the need to force type conversions when fetching data, reducing the code's running exception errors.
We know that an array is a collection of the same data type, and the disadvantage is that the capacity of the array is fixed and cannot be expanded dynamically. If a collection makes a qualification on the object type placed therein, it can also be seen as an "array" (collection) of objects of the same object type and capable of dynamically expanding the capacity. This allows us to know the type of data when we are depositing and extracting data, and generics are the implementation of the functionality that provides this idea.
code Reuse : There are also explanations for dynamic functions, which can be automatically matched according to the type that the runtime passes.
1) Generic class
public class demo<e>{
Private e E;
Demo (e e) {
this.e=e;
}
Public E Gete () {
return e;
}
}
String b= "Hello";
Demo Demo=new Demo (String b);
String A=demo.gete ();
Demo Demo1=new Demo (30);//This is not a basic type, but is automatically encapsulated as an integer object pass.
Integer Iter=demo1.gete ();
As can be seen from the above, by passing different reference types to the class, you can get the corresponding reference type object.
2) Generic method (generic method does not have a definite relationship with a generic class, can be a normal class, but a method in a class is a generic method)
public class test{
Public <E> void Demo (e e) {
System.out.println (E.class.getname ()); The name of the output class object
}
Public <E> e Demo1 (e e) {
....
return e;
}
}
3) Generic interface
public interface test<e>{
.....
}
4) wildcard characters? If not? You can pass an object or its subclasses into the type's qualification. (Any class can)
? Extends e: Represents a subclass that can only be passed into E or E.
? Super E: Represents the parent class that can only pass E or E.
5) Multi-generics
? Extends E & Interface Name & Interface Name 1 ..... class that represents E and its subclasses and implements the following interface.
Java-Generic Learning