|
Page 1 of 3 In part one of this series of articles, we had a look at generics and how they can make a difference to the way you code Java.
In this second part, I will cover two major features introduced in
J2SE 5.0 , ?Enhanced For Loop? and ?Autoboxing/Unboxing ?.Let?s start
with the enhanced for Loop.
Enhanced For Loop
First of all, have a look at the traditional approach of writing a for loop to iterate over the arrays/collections. Then we can understand why the new for loop is termed as Enhanced.
Listing 1
List mylist = new ArrayList();
mylist.add(new Integer(10));
mylist.add(new Integer(99));
for (int i=0; i < myList.size(); i++) {
Integer mynum = (Integer)mylist.get(i);
System.out.println("mynum>> " + mynum);
}
In the above code we can see that to iterate over an Arraylist we use an Iterator. to iterate over mylist.
Then in for loop we cast each object from mylist into an Integer
New Approach:
Listing 2
List mylist = new ArrayList();
mylist.add(new Integer(10));
mylist.add(new Integer(99));
for(Integer mynum:mylist) {
System.out.println("mynum>>"+mynum);
}
Listing 2 shows the new changed syntax of for loop. In the above code ArrayList has been defined and two elements have been added to it. In blue note the new for loop.
<< Start < Previous 1 2 3 Next > End >>
|