[J2SE 5.0 Topics] [2.1] Wild
A friend who has used C / C will not be unfamiliar with the word "generics"? I believe that friends with some Java encoding experiences or less encountered methods of using the collection class must be handmade. Look into the example below: Import java.util.ArrayList; import java.util.ITerator;
Public class myGenerics {
Public static void main (String [] args) {usenongenerics (); usegenerics ();} private static void useenongenerics () {arraylist alist = new arraylist (); alist.add (new integer (7)); alist.add ( New Integer (17)); int sum = 0; iterator it = alist.iterator (); while (ore.hasnext ()) {Sum = ((Integer) iter.next ()). INTVALUE ();} System SYSTEM .out.println (sum);} private static void usegenerics () {ArrayList alist = new arraylist (); alist.add (new integer (7)); alist.add (new integer) ); Int sum = 0; iterator ney = alist.iterator (); while (itute.hasnext ()) {SUM = iter.next (). INTVALUE ();} system.out.println (SUM) In this example I provide two different ways to complete the same thing, the example itself is meaningless, I just wants you to see some code that actually uses generic code in Java. The advantage of generics is that it can avoid type conversions we don't need to consider, and can provide type security checks for compile periods. (Note, in the above example, if you do not use generics, we can convert objects returned by iter.next () to any type, then call the type of method without throwing any compile periods). The introduction of generics has also laid the foundation for the emergence of template classes and template methods. If there is time, I suggest you take the source code of the new java.util.collection to take a look, you can fully support our support generic API.