J2se a friend of C + + is not unfamiliar with the word "generics"? I believe that some friends who have some Java coding experience have more or less encountered situations in which a type conversion must be done manually when using a method of a collection class. Look at the following example:
import java.util.ArrayList;
import Java.util.Iterator;
public class Mygenerics {
public static void Main (string[] args) {
Usenongenerics ();
Usegenerics ();
}
private static void Usenongenerics () {
ArrayList alist = new ArrayList ();
Alist.add (New Integer (7));
Alist.add (New Integer (17));
int sum = 0;
iterator iter = Alist.iterator ();
while (Iter.hasnext ()) {
sum + = ((Integer) Iter.next ()). Intvalue ();
}
System.out.println (sum);
}
private static void Usegenerics () {
arraylist<integer> alist = new arraylist<integer> ();
Alist.add (New Integer (7));
Alist.add (New Integer (17));
int sum = 0;
iterator<integer> iter = Alist.iterator ();
while (Iter.hasnext ()) {
sum = Iter.next (). Intvalue ();
}
System.out.println (sum);
}
}
In this example I have provided two different ways to do the same thing, the example itself has no meaning unimportant, I just want you to see some code that actually uses generics in Java.
The advantage of
generics is that it avoids type conversions that we don't need to consider, and can provide a type security check for compile-time. (note, in the example above, if you do not use generics, then we can convert the object returned by Iter.next () to any type, and then call that type of method without throwing any compile-time exceptions. The introduction of generics also lays the groundwork for the appearance of template classes and template methods.
If you have time, we suggest that the new java.util.Collection to take a look at the source, you can fully implement your own support generic API.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.