First, a simple example
classSolution<t> { PrivateT obj; Solution (T obj) { This. obj =obj; } PublicT getobj () {returnobj; } Public Static voidMain (string[] args) {solution<Integer> solution =NewSolution<> (100); Object obj=solution.getobj (); System.out.println (Obj.getclass (). GetName ());//Java.lang.IntegerSystem.out.println (obj);// - }}
View Code
Ii. Types of safety
If you simply use object as an alternative to generics and ensure that the type is converted correctly, you will get the same functionality even if you do not apply generics. However, if the type conversion is not correct, the program will be at run time error, the use of generics can automatically ensure type safety, the process of eliminating the need for manual input type conversion and type checking, run-time errors can be converted to compile-time errors, this is the primary advantage of generics.
Three or more types of parameters
classSolution<t, v> { PrivateT Obja; PrivateV OBJB; Solution (T Obja, V objb) { This. Obja =Obja; This. OBJB =OBJB; } PublicT Getobja () {returnObja; } PublicV getobjb () {returnOBJB; } Public Static voidMain (string[] args) {solution<character, integer> solution =NewSolution<> (' 0 ', 0); System.out.println (Solution.getobja ()); System.out.println (SOLUTION.GETOBJB ()); }}
View Code
Iv. bounded types
Restricts the types that can be passed to a type parameter by specifying a superclass.
classSolution<textendsNumber> { Privatet[] arr; Doublegetsum () {Doublesum = 0; for(T i:arr) sum+=I.doublevalue (); returnsum; } solution (T ... nums) {arr=Nums; } Public Static voidMain (string[] args) {solution<Integer> solution =NewSolution<> (1, 2, 3, 4, 5); System.out.println (Solution.getsum ()); }}
View Code
In addition to specifying a superclass as a boundary, you can also specify an interface as a boundary.
Five, wildcard parameters
boolean samesum (solution<t> ob) { return getsum () = = ob.getsum ();}
View Code
Suppose we need to compare objects of the same type with different generic parameters, the code above does not meet the requirements. The above code can be called only if the comparison object has the same generic parameter. The correct solution requires a wildcard character, which can also be specified as bounded.
classSolution<textendsNumber> { Privatet[] arr; Doublegetsum () {Doublesum = 0; for(T i:arr) sum+=I.doublevalue (); returnsum; } BooleanSamesum (solution<?extendsNumber>ob) { returnGetsum () = =ob.getsum (); } solution (T ... nums) {arr=Nums; } Public Static voidMain (string[] args) {solution<Integer> Solutiona =NewSolution<> (1, 2, 3, 4, 5); Solution<Double> solutionb =NewSolution<> (5.0, 4.0, 3.0, 2.0, 1.0); System.out.println (Solutiona.samesum (SOLUTIONB));//true }}
View Code
Vi. generic methods
classSolution {Static<textendsNumber, VextendsNumber>Booleancontain (t[] arr, V x) { for(inti = 0; i < arr.length; i++) if(Arr[i].doublevalue () = =X.doublevalue ())return true; return false; } Public Static voidMain (string[] args) {double[] arr= {1.0, 2.0, 3.0, 4.0, 5.0}; SYSTEM.OUT.PRINTLN (arr, contain1)); }}
View Code
Constructors also support generics.
class Solution { privatedouble number ; extends Number> solution (T t) { = t.doublevalue (); }}
View Code
Seven, generic interface
Generic interfaces are similar to generic classes.
InterfaceMinmax<textendsComparable<t>>{T min (); T Max ();}classSolution<textendsComparable<t>>ImplementsMinmax<t> { Privatet[] arr; @Override PublicT min () {T res= Arr[0]; for(inti = 1; i < arr.length; i++) if(Res.compareto (arr[i]) > 0) Res=Arr[i]; returnRes; } @Override PublicT Max () {t res= Arr[0]; for(inti = 1; i < arr.length; i++) if(Res.compareto (Arr[i]) < 0) Res=Arr[i]; returnRes; } solution (T ... nums) {arr=Nums; } Public Static voidMain (string[] args) {solution<Integer> OB =NewSolution<> (1, 2, 3, 4, 5); System.out.println (Ob.min ()); System.out.println (Ob.max ()); }}
View Code
Viii. Legacy of History
Early Java was not supported for generics, and there are still a lot of historical legacy code. In order for these legacy code retention features to be compatible with generics, Java allows the use of generic classes without supplying any type parameters, which creates the original type for the class. The original type is compatible with legacy code that does not use generics, but it loses the generic type security. Essentially, an object is used to replace the type represented by the type parameter.
class Solution<t> { private T ob; Solution (T ob) { this. OB= ob; } T Getob () { return ob; } Public Static void Main (string[] args) { new solution (new String ("Hello World")); System.out.println (Solution.getob ());} }
View Code
Nine, the generic class level
Use generic superclass.
class A<t> { T A; A (T a) { this. A= A; } T Geta () { return A; }} class extends A<t> { V b; B (T A, V b) { Super(a); this. B = b; } V Getb () { return b; }}
View Code
Generic hierarchy comparison.
class Solution { publicstaticvoid main (string[] args) { BNew b<> ("Hello", "World"); instanceof a<?>); // true }}
View Code
When you need to cast a generic class, you must ensure that it is compatible with each other and that the generic parameters are the same.
X. Erase
To be compatible with previous versions of Java, any modifications to the Java language syntax or virtual machines must avoid breaking the previous code, so Java uses Erasure to implement generics.
How erasing works: When compiling Java code, all generic information is erased. Then you must replace the type parameter with their defined type, and if you do not explicitly specify a defining type, object is used. The appropriate type conversions are then made to maintain compatibility with the type specified by the type parameter. This means that the Java generics are only a source code mechanism when there are no type parameters allowed at all times, and the type conversions at runtime inevitably entail overhead.
Xi. Ambiguity Error
class Solution<t, v> { private T A; Private V B; Solution (T A, V b) { this. A = A; this. B = b; } void set (T a) { this. A = A; } void Set (V b) { this. B = b; }}
View Code
The above code has a fuzziness error and cannot determine the method being called when T and V are of the same type.
12. Restrictions
- You cannot instantiate an object or an array of type parameters.
- A static member cannot use a type parameter declared in a class.
- Generic classes cannot extend Throwable, that is, you cannot create generic exception classes.
To instantiate an array of generic objects, you need to use a wildcard character.
class Solution<t> { publicstaticvoid main (string[] args) { SolutionNew solution<integer>[10]; // Error New solution<?>[10]; // correct }}
View Code
Java notes: Generics