Java Generics: Compiled From Core Java
Java Generics: Compiled From Core Java
import java.util.*;
public class First {
public static void main(String args[]) {
List<Integer> myList = new ArrayList<Integer>(10);
myList.add(10); // OK ???
myList.add("Hello, World"); // OK ???
}
}
Generics (cont’d)
Example (compile-time exception):
import java.util.*;
public class First {
public static void main(String args[]) {
List<Integer> myList = new ArrayList<Integer>(10);
myList.add(10); // Autoboxing converted the int type to an Integer
myList.add("Hello, World");
}
}
import java.util.*;
public class Second {
public static void main(String args[]) {
List list = new ArrayList();
list.add(10); // the "E" in the "add(E)" call, was never specified.
}
}
When you compile the program, you get the following warning:
import java.util.*;
public class Second {
public static void main(String args[]) {
List<Object> list = new ArrayList<Object>();
list.add(10);
}
}
If you compile and run the Old class and then run it with a string, like
this:
java Old Hello
you get: Hello / 5
Generics (cont’d)
Another example:
// old way of looping through a List of String objects
// without generics and an enhanced for loop
import java.util.*;
public class New {
public static void main(String args[]) {
List<String> list = Arrays.asList(args);
for (String element : list) {
System.out.println(element + " / " + element.length());
}
}
}
Generics
• http://java.sun.com/j2se/1.5.0/docs/guide/lang
uage/generics.html