Ten generics
Generics can be understood as tags
The collection container class cannot specify its specific storage type in the design declaration stage,
Before JDK5, the element type can only be set to Object
After JDK5, generics are introduced. At this time, parameters are used on the container to determine the type stored in the container
Such as collection, list and ArrayList, where is the type parameter: generic
In this way, E will be assigned a value (pass in the parameter) when it is actually used
10.1 using generics in Collections
No generics
ArrayList list = new ArrayList(); list.add(1); list.add(3); list.add(5); list.add("sdf");//All are complete and correct. There will be no problem in compiling, but the type is not safe. If list is used to store score data, the runtime may be abnormal for(Object score: list){ int stuScore = (Integer)score;//Forced conversion is required because the score is of type Object }
Use Generics
A generic type is a type and cannot be a base data type
ArrayList<Integer> list = new ArrayList<Integer>();//Cannot be int list.add(1); list.add("dsf");//An error is reported. Type check is performed during compilation to ensure data security //Mode 1 for(Integer score:list){ int stuScore=score;//You don't have to turn around here } //Mode II Iterator<Integer> iter = list.iterator(); while(iter.hasNext()){ sout(iter.next()); }
HashMap
Map<String,Integer> amp = new HashMap<>();//After JDK7, the < > after new can be omitted: type inference map.put("sd",1); map.put("sdf",2); Set<Map.Entry<String,Integer>> entry = map.entrySet(); for(Entry en: entry){ en.getkey(); en.getValue();W } //or Iterator<Map.Entry<String,Integer>> iter =entry.iterator(); while(iter.hasNext()){ Map.Entry<String,Integer> e = iter.next(); e.getKey; e.getValue; }
10.2 custom generics
10.2.1 generic class, generic interface
Generally, the setting of generic letters
K V key value T class E method
public class Order<T>{ String orderName; int orderId; T orderT; public Order(){} public Order(... , T orderT){ this. .... this.orderT=orderT; } public T getOrderT(){ return orderT; } } //If the generic type is not specified during instantiation, it defaults to Object type Order o = new Order<String>();//I'm not used to writing at the beginning. The front < > is particularly easy to forget Order<String> o =new Order<>();
Inheritance:
//Indicate generics when inheriting public class SubOrder extends Order<String>{ .... } SubOrder sub = new SubOrder("aa",1,"OrderT"); //Inheritance is not specified public class SubOrder<E,T> extends Order<T>{ E subOrderE; ... } SubOrder<int,String> subOrder = new SubOrder<>();
class Fu<T1,T2>{ } class Z1 extends Fu{} // Equivalent to class Z1 extensions Fu < object, Object > class Z2 extends Fu<String,Integer>{ } //Specific types are indicated class Z3<T1,T2> extends Fu<T1,T2>{ }//remove none class Z4<T2> extends Fu<Integer,T2>{ }//Partial retention
When a class is instantiated into two different generic objects, it doesn't matter to each other. It can't assign values to each other (it can't pass the compilation)
Exception classes cannot have generics
You cannot have generics in a static member method. Simply put, there are generic letters from the first p to the last} end
Not in the trycatch of the ordinary member method.
T[] arr =new T[10 ]; no way!
T[] arr = (T[ ]) new Object[10];
10.2.2 generic methods
What's the generic method?
It doesn't mean that generics that use classes in generics are called generic methods,
//This is not a generic method int add(E e); public List<E> copyXxxx(E[] arr){//The compiler will treat E [] as an array of declared types //That's it <T> T[ ] toArray(T[ ] a); public <E> List<E> copyXxxx(E[] arr){ } //Method use List<Integer> list = Order.copyXxxx(new Integer(){1,2,3});//The parameters passed in determine the type of E
Generic methods can make static!!!!
Because generic parameters are determined at call time, class initialization is not required
However, we should distinguish between the generics of generic methods and the generics of classes in methods
10.2.3 example: DAO class
data(base) access object
The problem is that there are many tables of various types. It's too troublesome to write, add, delete, modify and check each type of data. So use generics
Approach: let each table in the database correspond to a class in java, and operate the object of the operation class corresponding to each table. What kind of class does it correspond to?? Corresponding T
public class DAO<T>{ //increase public void add(T t){ ... } //Delete public boolean remove(int index){...} //change public void update(int index,T t){...} //check public T getIndex(int index){return null} pubcli List<T> getFullIndex(int begin,int end){return null} //generic method public <E> E getValue(){ //For example: get the total number of records in the table: E is assigned integer Long //Another example: obtain the salary of all employees, and the value of E is floating point return null; } } //Customer table public class Customer{ String name; ... } public class customerDAO extens DAO<Customer >{ //Empty, write nothing } //Student list public class Student{ ... } public class StudentDAO extends DAO<Student>{//Each xdao can only operate on the corresponding table } //test public class DAOTest{ @Test public void test1(){ CustomerDAO dao1 =new CustomerDAO(); dao.add(new Customer()); List<Customer> list = dao.getFullIndex(10,13); } @Test public void test2(){ StudentDAO dao =new STudentDAO(); dao.add(...); } }
10.3 generic inheritance
List<Object> list=null; List<String> list3=null; list=list3;//An error is reported. Generics cannot be polymorphic //G < Fu > and G < Zi > are completely different types and have no father son relationship, but they have a public father, G <? > See below for details
10.4 use of wildcards
10.4.1 <?>
If you want to write a general List traversal function, Int type, String type and Person type
But < > there is no polymorphism,
Wildcard:?
List<Object> list1 = null; List<String> list3 = null; LIst<?> list= null; list = list1;//All right list = list3;//All right public void show(List<?> list){ Iterator<?> iter = list.iterator(); while(iter.hasNext()){ Object o = iter.next(); sout(obj) } }
After using wildcards, you can't add add as usual
In addition to adding null
10.4.2 restricted wildcards
//Only Person and its parent classes are allowed The generic type under super restriction can be add ed