First, what is generics?
Java generic design principle: As long as there is no warning at compile time, there will be no ClassCastException exception at run time.
Generics: Delay typing until you create an object or call a method to specify a particular type
Parametric types:
E in ArrayList < E > is called type parameter variable
Integer in ArrayList < Integer > is called the actual type parameter
The whole is called the ArrayList < E > generic type
The entire ArrayList < Integer > is called the parameterized type ParameterizedType
2. Why generics are needed
With generics:
- Code is more concise [no mandatory conversion]
- Programs are more robust [ClassCastException exceptions do not occur at runtime as long as there is no warning at compile time]
- Readability and stability [Types are defined when collections are written]
When creating collections, we have defined the types of collections, so we can use enhanced for to traverse collections!
//Creating Collection Objects ArrayList<String> list = new ArrayList<>(); list.add("hello"); list.add("world"); list.add("java"); //Traverse, because the type is clear. We can enhance for for (String s : list) { System.out.println(s); }
3. Generic Basis
Generic classes are defined on classes. When users use this class, they define the type clearly. In this way, the user specifies what type it is and what type it represents. Users don't have to worry about the problem of forcing when they use it, but the problem of exceptional runtime conversion.
Generics defined on classes can also be used in class methods!
/* 1:Define generics on classes 2:Type variables are defined on classes and can also be used in methods. */ public class ObjectTool<T> { private T obj; public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; } }
The type that the user wants to use is specified at the time of creation. When used, the class is automatically converted to the type the user wants to use.
public static void main(String[] args) {
//Create objects and specify element types ObjectTool<String> tool = new ObjectTool<>(); tool.setObj(new String("Zhong Fu Cheng")); String s = tool.getObj(); System.out.println(s); //Create objects and specify element types ObjectTool<Integer> objectTool = new ObjectTool<>(); /** * If I pass in String type in this object, it won't pass at compile time. */ objectTool.setObj(10); int i = objectTool.getObj(); System.out.println(i);
}
Define generic methods... Generics are defined first and then used
//Define generic methods. public <T> void show(T t) { System.out.println(t); }
What type is the user passing in and what type is the return value?
public static void main(String[] args) { //create object ObjectTool tool = new ObjectTool(); //Call the method, what type of parameter is passed in, and what type is the return value? tool.show("hello"); tool.show(12); tool.show(12.5); }
Subclasses specify type parameter variables for generic classes
/* Define generics on interfaces */ public interface Inter<T> { public abstract void show(T t); }
Classes that implement generic interfaces... ..
/** * Subclasses specify type parameter variables for generic classes: */ public class InterImpl implements Inter<String> { @Override public void show(String s) { System.out.println(s); } }
IV. Application of Generics
When we write web pages, we often have multiple DAOs. We have to write several DAOs every time, which will cause some trouble.
public abstract class BaseDao<T> { //Simulate hibernate... private Session session; private Class clazz; //Which subclass to tune this method, the resulting class is the type of subclass processing (very important) public BaseDao(){ Class clazz = this.getClass(); //You get subclasses. ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass(); //BaseDao<Category> clazz = (Class) pt.getActualTypeArguments()[0]; System.out.println(clazz); } public void add(T t){ session.save(t); } public T find(String id){ return (T) session.get(clazz, id); } public void update(T t){ session.update(t); } public void delete(String id){ T t = (T) session.get(clazz, id); session.delete(t); } }
Inheriting Abstract DAO, the implementation class has corresponding methods of adding, deleting and modifying.
public class CategoryDao extends BaseDao<Category> { } BookDao public class BookDao extends BaseDao<Book> { }