Friday, May 9, 2008

J2SE 5.0 Language Features

J2SE5.0 has the following noteworthy language features.

Enhanced For Loop

The new enhanced for loop provides a simple, consistent syntax for iterating over collections and arrays.

Consider the following example. A collection companies contains the following names: Sun, BEA Weblogic, Oracle.

Accessing the collection without enhanced loop.

for(Iterator it = companies.iterator();it.hasNext();){//Line1
String cmp = (String)it.next();//Line2
System.out.println(cmp);
}


We need to declare Iterator(Line1), type cast the value(Line2) to access the value.

This is prone to error for the following reasons.
1. Use of Iterator
2. TypeCasting, since the Type of data in Collection companies might not be known until run-time.

Accessing the collection with enhanced loop.

for(String it:companies){
System.out.println(it);
}


The use of : reads as for each string it in companies. This approach is cleaner and robust. It does not make use of Iterator and TypeCasting is not required(The compiler takes care of these thing in background).

Enhanced loop Limitations

It cannot be used to traverse collection in which we need to add or remove entries.

for(Iterator it = companies.iterator();it.hasNext();){
if(it.next().equals("Oracle")){
it.remove();
}
}


From the above code we can see that in order to remove Oracle from the collection, we need to iterate the collection.

Sample Code For Enhance for Loop

public void EnhancedForLoop() {
List companies = new ArrayList();

companies.add("Sun");
companies.add("BEA Weblogic");
companies.add("Oracle");

// Without Enhanced
for (Iterator it = companies.iterator(); it.hasNext();) {
String cmp = (String) it.next();
System.out.println(cmp);
}

// With Enhanced
for (String it : companies) {
System.out.println(it);
}

// Without Enhanced
for (Iterator it = companies.iterator(); it.hasNext();) {
if (it.next().equals("Oracle")) {
it.remove();
}
}
System.out.println(companies);
}


Annotations

Generics

No comments: