Collection_Generics1 |
The choices to make, strict data type protection or relaxed with the
data type. This example is one of the unorthodox type, and is used to
compare Collections and Generics. |
Below is an example of using "List" Interface in Collection
Framework. Collections is further enhanced by Generics handling compile
time error due to wrong casting of data-types; (with Eclipse::Kepler) |
(update of this example : Collection_Generics2.htm) |
Below is a static method to iterate a list object as a parameter,
uses a Generic enhancement List<Object> list, over this parameter


The above uses a Static method.
|
If you note the warnings sign adjacent to "List" interface , it is a
type safety warning.
In the screen shot below showing code update from collections to
Generics.

|
Code :
import java.io.*;
import javax.swing.JOptionPane;
import java.net.URI;
import java.util.*;
public class ClassTemplate1 {
public ClassTemplate1() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
throws Exception {
// TODO Auto-generated method stub]
Process pp = new Process();
try {
//Without Generic
List alist = new ArrayList();
alist.add("hello");// at index 0
alist.add(123); // at index 1
int n1 = (int)alist.get(1);
String s1 = (String) alist.get(0);
pp.roller(alist);
Process.roller(alist);
//with Generic
List<Object> olist = new ArrayList<Object>();
olist.add("hello");
olist.add(123);//
Object s2 = olist.get(0); // no cast
System.out.println(s1 + " " + n1 + " " +s2);
Process.roller(olist);
//
} catch (NumberFormatException exc) {
//Process
}
}
}// end of class template
//
//outer class
class Process
{
public Process() {
System.out.println("Process outer constructor");
}
public static void roller(List<Object> list)
{
ListIterator<Object> iter = list.listIterator();
//
while(iter.hasNext()){
System.out.println("\t" + iter.next());
}
}
}
|
|
|
|