| Collection_Generics2 |
| Note: 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. |
Recap:
|
| Collection to Generics (used Eclipse ::Kepler) |
| Processing with List
Entry Point with main method:( image splitted into two)
|
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]
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); //casting integer
String s1 = (String) alist.get(0);//casting string
System.out.println("--->- printing non-generic");
System.out.println("\t printing variables: after casting ");
System.out.print("\t"+s1 + " , " + n1 );
System.out.println("");
System.out.println("Non-Gereic : print with iterator::indexed");
Process.roller(alist);// calling a method
//with Generic
List<Object> olist = new ArrayList<Object>();
olist.add("a string as : Hello");
olist.add("string and int "+ 123);
olist.add( 456 );
Object s2 = olist.get(0); // no cast
Object s3 = olist.get(1);
Object s4 = olist.get(2);
//displaying data
System.out.println("");
System.out.println("---->> print generics : ");
System.out.println("\t printing variables :no casting");
System.out.print("\t"+s2 + " " + s3 + " " +s4);
System.out.println("");
System.out.println("Generics :print with iterator::indexed");
Process.roller(olist);
//
} catch (NumberFormatException exc) {
//Process
}
}
}// end of class template
//
//Processing with ListIterator
class Process
{
public Process() {
System.out.println("Process outer constructor");
}
public static void roller(List<Object> list)
{
ListIterator<Object> iter = list.listIterator();
System.out.print("\t");
while(iter.hasNext())
{ System.out.print(iter.nextIndex()+
" : " + iter.next() +", ");
}
}
}
|
| Runtime Views:
|