1. Generics Overview
Generics are a special type that defers the work of a specified type until the client code declares and instantiates a class or method. Also known as a parameterized type, you can pass the type as a parameter, which is not clear until it is passed, but is clear when used.
Generics are new features that occur after JDK5.
2. Why generics occur 1
Package Com;import Java.util.arraylist;import Java.util.iterator;public class Genericdemo {public static void main ( String[] (args) {//Create collection Object ArrayList list = new ArrayList ();//add Element List.add ("Hello"); List.add ("World"); List.add ("Java") ;//traversal for (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {string str = (string) iterator.next () ; System.out.println (str);}}}
Hello
World
Java
The above code is to put the string into the collection, but the collection of the parameter type of the Add () method when the object, so we can put any reference type, of course, if you are storing the basic type, then JDK5 will have automatic boxing function, the basic type into a reference type, remember, The collection holds the reference type, not the base type. Although you can store basic types of data, the bottom of the JDK is still converted to reference data types. If you don't understand it, you can use the Anti-compilation tool to decompile the bytecode file and know it.
Package Com;import Java.util.arraylist;import Java.util.iterator;public class Genericdemo {public static void main ( String[] (args) {//Create collection Object ArrayList list = new ArrayList ();//add Element List.add ("Hello"); List.add ("World"); List.add ("Java"); List.add (new Integer); List.add (10);//auto-boxing//Traversal for (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {string str = (string) iterator.next (); System.out.println (str);}}}
Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String
at COM. Genericdemo.main (GENERICDEMO.JAVA:18)
Error, type conversion exception, meaning that an integer type cannot be converted to a string type. This is a run-time exception, which means that the exception is generated during runtime, which is inconvenient.
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/88/F3/wKioL1gCxUagkmR3AAAnyBnLsU4266.jpg "title=" Link.jpg "alt=" Wkiol1gcxuagkmr3aaanybnlsu4266.jpg "/>
So at this point, let's review the array of type string
string[] str = new String[10];str[0] = "Hello"; str[1] = "world"; str[0] = 12;//This is a direct error during compilation, why? Because it is an array of type string,//you actually store data of type int
Similarly, can we use this mechanism when defining a set?
Of course, the collection also uses the mechanism of defining the data type of the element when creating the collection object, so that the problem does not occur. This technique is called generics.
So at this point, let's look at the definition of generics, which is a special type of explicit work that is deferred until the object is created or the method is called. In other words, it is not very convenient to define the collection class, not to give a specific type, when you create a collection object to give a specific type, to limit the collection type of all types.
But the type here can only be a reference type, not a basic type Oh, remember that although there are JDK5 automatic boxing and unpacking features. But the collection essentially holds the data of the reference type, so when you create the collection object, use the generic to reference the data type Oh, because the JDK is not so powerful, haha.
Package Com;import java.util.arraylist;import java.util.iterator;//error code public class Genericdemo {public static void Main (string[] args) {//Create collection Object Arraylist<string> list = new arraylist<string> ();//add Element List.add ("Hello"); List.add ("World"); List.add ("Java"); List.add (new Integer (100));//This code directly errors during compile time//Because we declare that all elements in the collection must be of type string, And we are storing other types of data list.add (10);//auto-boxing//and the same as above//traversal for (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {string str = (string) iterator.next (); System.out.println (str);}}}
3. Benefits of Generics
So at this point, let's think, since generics can limit the data type of a collection element, it means that all the types in the collection are the same, oh, so we can omit the type conversion when we take the string out? Think of a string type array, and when you iterate over it, do you consider the type conversion? No, because I know that the array is stored in the string type of data, I certainly do not have to consider, then the benefits of generics, is to eliminate the problem of type conversion.
The original code
Package Com;import Java.util.arraylist;import Java.util.iterator;public class Genericdemo {public static void main ( String[] (args) {//Create collection Object Arraylist<string> list = new arraylist<string> ();//add Element List.add ("Hello"); List.add ("World"); List.add ("Java");//Traversal for (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {String str = (string) iterator.next ();//Type conversion System.out.println (str);}}}
Now that we know that generics omit type conversions, what do we do to enforce the markup for type conversions at this point?
Package Com;import Java.util.arraylist;import Java.util.iterator;public class Genericdemo {public static void main ( String[] (args) {//Create collection Object Arraylist<string> list = new arraylist<string> ();//add Element List.add ("Hello"); List.add ("World"); List.add ("Java");//Traversal for (iterator<string> Iterator = List.iterator (); Iterator.hasnext ();) {String str = iterator.next ();//Type conversion System.out.println (str);}}}
Of course, because I used the iterator to limit the iterator to the generic string type, so that the next time the elements in the collection is not type conversion, is not very convenient ah, such a function is great. It is really hard to JDK4 before the programmer, to do the type conversion.
Summarize the benefits of generics:
1. Improve the security of the program
2. Transfer problems encountered during the run to compile time
3. Eliminates the hassle of forcing type conversions
4. Where are generics used?
View API, if the class, interface, abstract class followed by a tag such as <E>, it means to use generics. In general, it is used in collections.
package com;import java.util.arraylist;import java.util.iterator;import Java.util.listiterator;public class arraylistdemo {public static void main ( String[] args) {//Create ArrayList object arraylist<string> list = new arraylist< String> ();//add Element List.add ("haha"); List.add ("hehe"); List.add ("Hee-hoo"); List.add ("stupid");//traversal mode one Replace the ArrayList collection with the Object[]object[] obj = list.toarray ();for (int i = 0; i < obj.length; i++) {String str = (String) obj[i]; System.out.println (str);} System.out.println ("----------------------");//Traverse mode two use Iterator iterator for (iterator<string> Iterator = list.iterator (); Iterator.hasnext ();) {string str = iterator.next (); System.out.println (str);} System.out.println ("-----------------------");//Traverse Mode III use Listiterator iterator//forward traverse listiterator<string> listiterator = list.Listiterator (); while (Listiterator.hasnext ()) {string str = listiterator.next (); System.out.println (str);} System.out.println ("------------------------");//Reverse Traversal while (listiterator.hasprevious ()) {string str = listiterator.previous (); System.out.println (str);} System.out.println ("------------------------");//Traverse mode four use the size () and get (Int index) methods to implement traversal of the collection element for ( Int i = 0; i < list.size (); i++) {String str = List.get (i); System.out.println (str);}}}
5. Why generics occur 2
Early object types can receive arbitrary types of objects, but in actual use there is a type conversion problem. There is a security risk, so Java provides generics to address this security issue.
6. Generics applications
Generic class:
Defines a generic type on a class.
Format: public class name < generic type 1, generic type 2,... >
Note: The generic type must be a reference type
Package com;/** * Generic type */public class Objecttool<t> {private T obj;public T Getobj () {return obj;} public void Setobj (T obj) {this.obj = obj;}} Package com;/** * Generic class Test * @author Hu Weiwei * */public class Objecttooltest {public static void main (string[] args) {Objecttool <String> ot = new objecttool<string> (); Ot.setobj ("haha"); System.out.println (Ot.getobj ());objecttool<integer> Ot2 = new objecttool<integer> (); Ot2.setobj (20);// Auto Boxing System.out.println (Ot2.getobj ());}}
Generic methods:
Defines a generic type on a method.
Format: Public < generic type > Return value type method name (generic type 1, generic type 2,...)
Package Cn;public class Objecttool {public void Show (String str) {System.out.println (str);} public void Show (Integer i) {System.out.println (i);}} Package Cn;public class Objecttooltest {public static void main (string[] args) {objecttool ot = new Objecttool (); Ot.show (" Haha "); Ot.show (20);//Auto-boxing}}
This is true, but if I pass in a Boolean type, student type, then I can only modify the Objecttool class, continue to increase the overloaded method, good trouble.
Package Cn;public class Objecttool<t> {public void show (T t) {System.out.println (t);}} Package Cn;public class Objecttooltest {public static void main (string[] args) {objecttool<string> ot = new Objectto Ol<string> (); Ot.show ("haha");objecttool<integer> Ot2 = new objecttool<integer> (); Ot2.show (+); O bjecttool<boolean> ot3 = new objecttool<boolean> (); Ot3.show (True);}}
However, is the above code consistent with the type of the parameter on the generic method and the class, but if there is no generic on my class, the method cannot accept any type of data? Of course not. and see below decomposition.
Package Cn;public class Objecttool<t> {public void show (T t) {System.out.println (t);}} Package Cn;public class Objecttool1test {public static void main (string[] args) {ObjectTool1 ot = new ObjectTool1 (); Ot.sho W ("HelloWorld"); ot.show (100);}}
Generic interface
Defines a generic type on an interface.
Format: public interface interface name < generic type 1, generic type 2,... >
Package Cn;public interface Objecttool3<t> {public void show (T t);} Package Cn;public class Objecttool3test {public static void main (string[] args) {objecttool3<string> ot = new Object Tool3<string> () {public void Show (String str) {System.out.println (str);}};o T.show ("hehe");}}
7. Wildcard Characters of generic type
<?> any type, if not explicit, is object and any type of Java class.
<? Extends e> down, E and its subclasses
<? Super e> up, E and its parent class
package cn;import java.util.arraylist;import java.util.collection;/** * Generic wildcard character * ? any type, if not explicit, is object and any Java class. * ? extends E down, E and its subclasses * ? super E up, E and its parent * */class animal{}class dog extends animal{}class cat extends animal{} Public class genericdemo {public static void main (String[] args) {// Generics if explicit, must be consistent collection<object> c = new arraylist<object> ();//The following three kinds will be error// Collection<object> c = new arraylist<animal> ();//Collection<Animal> c = new ArrayList<Dog> ();//collection<animal> c = new Arraylist<dog> (); Collection<?> c1 = new arraylist<animal> (); Collection<?> c2 = new arraylist<dog> (); Collection<?> c3 = new ArrayList<Cat> ();//? extends e downward limit, E and its subclasses collection<? Extends animal> c4 = new arraylist<dog> ();//? super E up limit, E and its parent class collection<? super animal> c5 = new Arraylist<object> ();}}
This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1862368
Java Collection Framework-generics