Java Generics

Generics: is a Mechanism in Java 1.5 (aka JDK 5) that allows us to template paramters while using Java Objects. What this does is tremendously reduce code to typed in.

import java.util.*;
public class Test { public Test() { }

public static void main(String[] args) {

List words = new ArrayList();

words.add("at");
words.add("bat");
words.add("cat");
words.add("dat");

for (Iterator i = words.iterator(); i.hasNext(); ) {
String s = i.next(); // Look MOM not CASTING !!!
System.out.println(s);
}

String s1="";

// new Kind of Looping with Generics

for(String x : words) // read as: For each x in Words
{ s1+=x;
System.out.println("s1 is " + s1);
}

System.out.println(s1); }
}
}


0 comments:

Post a Comment