Why use generics?
A generic program is designed primarily to write code that can be reused by different objects .
The simplest example is ArrayList. We cannot write a ArrayList for each object, and ArrayList is designed as a generic class for all objects. Some people say that without generics, using object is not possible? But with object, you have to force type conversions in front of specific objects.
Generic class
A generic class is another class of one or more type variables.
The following defines a generic type of coordinate class.
Public classPoint<t> { PrivateT x; PrivateT y; PublicT GetX () {returnx; } Public voidSetX (T x) { This. x =x; } PublicPoint (t X, t y) { This. x =x; This. y =y; } PublicPoint () {}}
View Code
This allows us to pass in the type we need, such as:
New Point<> (a); Pointnew point<>(1f,1f);
Generic methods
A generic method refers to a method with a type parameter.
class arrayutil{ publicstatic <T> T getmiddle (t[] array) { return ARRAY[ARRAY.LENGTH/2];} }
Generic interface
Generic interfaces are the same as generic class usages, such as:
Public Interface Javabeancrud<t> { T Getobjectbyid (String ID); void addobject (T obj); void Delobjbyid (String ID); void updateobj (T obj);}
Public Interface extends Javabeancrud<student> {}
public class studentdaoimpl implements Studentdao {@Override public Student Getobjectbyid (String id) { return null ; @Override public void public void Delobjbyid (String id) {} @Override public void Updateobj (Student obj) {}}
The simple example we can see is that generics do give us less rewriting of the code.
Qualification of type variables
If we need to write a method that implements getting the maximum value in the collection, the CompareTo interface is used. We can use extends to limit the types of variables. Such as:
public static <t extends comparable> T Getmax (t[] array) { if (Array==null | | array.length==0" return null ; T max = Array[0]; for (T temp:array) { if (Max.compareto (temp) <0) Max = temp; return Max; }
Extends here is no longer the meaning of our familiar inheritance. The object that is bound to getmax this method must inherit comparable, or there will be a compile error.
A type variable or wildcard can have more than one qualification, separated by ' & ', for example:
T extends comparable & Serializable
Java generics in-depth explanation