I. Concept 1. Why generics are needed?
When generics are not used:
publicclass Test01 { publicstaticvoidmain(String[] args) { new HashMap(); map.put("m1""sssss"); String str = (String)map.get("m1"); }}
After using generics:
publicclass Test01 { publicstaticvoidmain(String[] args) { new HashMap<>(); map.put("m1""sssss"); String str = map.get("m1"); }}
jdk1.5 the generics that appear, by < data type > to receive a reference data type, the role is to compile the program, use to check whether the object added in the collection is that type, so that the run-time problems to the compile time, improve the security of the program. Otherwise, the "Java.lang.ClassCastException" exception is easily seen. Use generics to solve this kind of problem.
This allows you to eliminate coercion of type conversions in your code and to obtain an additional type-checking layer that prevents someone from saving the key or value of the wrong type in the collection. This is the work that generics do.
Generic erase: Generics exist at compile time, and there is no generics in the bytecode file after compilation is complete.
2. Advantages and disadvantages of generics
Before generics occur, when we want to increase the extensibility of our programs, we often use object, but after generics appear, we are using generics more often.
Use Object
publicclass Tool { private Object obj; publicgetObj() { return obj; } publicvoidsetObj(Object obj) { this.obj = obj; }}
Using generics
publicclass Tool1<T> { private T t; publicgetT() { return t; } publicvoidsetT(T t) { this.t = t; }}
An entity class
publicclass Worker {}
Use contrast
Public classTest01 { Public Static void Main(string[] args) {//hashmap<string, string> map = new hashmap<> ();//Map.put ("M1", "Sssss");//String str = map.get ("M1"); //Use ObjectTool tool =NewTool (); Tool.setobj (NewWorker ()); Worker worker = (worker) tool.getobj ();//Using genericsTool1<worker> tool1 =NewTool1<> (); Tool1.sett (NewWorker ()); Worker worker1 = Tool1.gett (); }}
3. What is a generic type?
The so-called "generics", is "broad data type", arbitrary data type. The advent of generics avoids strong transitions and transfers errors to the compile time.
Generic format: Define the reference data type to manipulate by <>
In fact, the generic type of Java is to create a class that uses a type as a parameter. Just like the way we write a class, the method is such methods (String str1,string str2), and the values of the parameters str1 and str2 in the method are variable. The generic is the same, so write class Java_generics , where the side of the K and V is like the parameters of the method str1 and str2, is also variable.
The naming style of generic parameters is: It is recommended that you use concise name as the name of the formal type parameter (if possible, a single character). It is best to avoid lowercase letters, which makes it easily distinguishable from other common form parameters. Use T to represent a type, no matter when it is more specific than the type to differentiate it. This is often seen in generic methods. If there are multiple types of parameters, we may use the adjacent letters of T in the alphabet, such as S. If a generic function appears inside a generic class, it is best to avoid confusion by using the same name in the type arguments of the method and the type parameters of the class. The same is true for inner classes.
To write a generic class, note:
1) when defining a generic class, define a formal type parameter between "<>", for example: "Class TestGen ", where "K", "V" does not represent a value, but represents a type.
2) When instantiating a generic object, be sure to specify the value (type) of the type parameter after the class name, and write two times. For example:
TestGen t=new TestGen ();
3) ,extends in generics does not represent inheritance, it is a type-range limitation.
4. When do I use generics?
1. When the reference data type to be manipulated in the class is indeterminate
2. Define an object early to complete the extension, and now define generics to complete the extension. General application development in the use of generics less, more used in the framework or library design, in order to increase the scalability.
Two. Use of generics 1. Generic class
Look directly at the code:
public class Demo1 { Span class= "Hljs-keyword" >public void show (String s) {system.. println ( "show:" + s); } public void show (Integer i) {system.. println ( "show:" + i); } public static void main (string[] args) {Demo1 demo1 = new Demo1 (); Demo1.show (3 ); Demo1.show ( "111111" ); }}
publicclass Demo<T> { publicvoidshow(T t) { System.out.println("show:" + t); } publicstaticvoidmain(String[] args) { new Demo<>(); demo.show("hello"); new Demo<>(); demo1.show(2); }}
Compared to using generics and not using generics, we need to write two methods, and now one is done, the advantages of generics are self-evident.
Description
generics defined by a generic class are valid throughout the class, and if used by a method, then the object of the generic class is explicitly the type of operation, and the type of the operation is fixed, that is, the type of the method operation is fixed. The type of the parameter of a method is determined only if the generic type on the class is determined.
To allow different methods to manipulate different types, and the types are not deterministic, you can define generics on methods.
2. Generic methods
To allow different methods to manipulate different types, and the types are not deterministic, you can define generics on methods.
When a generic is defined on a method, it is placed in front of the return type, after the modifier.
publicvoidfun(E e) { System.out.println("show:" + e); }
new Demo<>(); demo1.fun("fdfdfdf"); demo1.fun(122);
All code:
Public classdemo<t> { Public void Show(T T) {System. out. println ("Show:"+ t); }//This E is irrelevant to the generic type of the class Public<E>void Fun(e) {System. out. println ("Show:"+ e); } Public Static void Main(string[] args) {Demo<string> Demo =NewDemo<> (); Demo.show ("Hello"); demo<integer> Demo1 =NewDemo<> (); Demo1.show (2); Demo1.fun ("FDFDFDF"); Demo1.fun (122); }}
Description
Static method generics have one need to note:
A static method cannot access a generic defined on a class, only a generic type can be defined on a method. The reason for this is because the class does not have a generic type when it is loaded, and then the object of the class is created before the class's generics are known.
publicstaticmethod (W w) { System.out.println("show:" + w); }
3. Generic interface
Look directly at the code
publicinterface Inter<T> { void show (T t);}publicclass InterImpl implements Inter<String> { @Override publicvoid show(String s) { }}
What if the class does not know the generic type when implementing the interface?
publicinterface Inter<T> { void show (T t);}publicclass InterImpl1<T> implements Inter<T> { @Override publicvoid show(T t) { }}
4. Wildcard characters (? )
Any type, which can improve his versatility.
Public classDemo4 { Public Static void Main(string[] args) {arraylist<string> list =NewArraylist<> (); List.add ("111"); List.add ("2222"); List.add ("333"); Diedai (list); }Private Static void Diedai(ArrayList list) { for(inti =0; I < list.size (); i++) {Object o = list.Get(i); System. out. println (o); } }Private Static void DieDai1(arraylist<?> list) { for(inti =0; I < list.size (); i++) {Object o = list.Get(i); System. out. println (o); } }Private Static<Q>void DIEDAI2(arraylist<q> Q) { for(inti =0; I < q.size (); i++) {Q q1 = q.Get(i); System. out. println (Q1); } }}
5. Generic qualification (extends, super)
Restricted generics refers to the range upper and lower bounds of a generic object that can be specified during operation of a generic type
Format:
上限: 声明对象: 类名称<? extends Person>对象名称 声明类:访问权限 类名称<泛型标识 extends 类> 这个尖括号里必须是person或者person的子类.就是你传过来的集合元素类型可以是person或者person的子类 下限: 声明对象: 类名称<? super Person>对象名称 这个尖括号里必须是person或者person的父类.就是你传过来的集合元素类型可以是person或者person的父类
Class info<t>{PrivateTvar; PublicTGetVar() {return var; } Public void SetVar(Tvar) { This.var=var; }} Public classtypetest { Public Static void Main(string[] args) {info< integer>i=Newinfo< integer> (); I.setvar ( -); Fun (i); } Public Static void Fun(info<? extends number> temp) {System. out. println ("Content"+temp.getvar ()); }}
6. Generic arrays
Public classtypetest { Public Static void Main(string[] args) {//integer i[]={1,2,3,4,5};//static initialization arrayInteger i[]= fun1 (1,2,3,4,5); Fun2 (i); } Public Static<T> t[]fun1(T...arg) {//variable parameters and generic arrays returnArg } Public Static<T>void fun2(T param[]) { for(T T:param) {System. out. Print (t+","); } }}
Three. References
https://yq.aliyun.com/articles/3311
Http://www.weixueyuan.net/view/6321.html
http://blog.csdn.net/u012152619/article/details/47253811
Java tamping Basic series: Generics