Wednesday, December 16, 2015

Enhanced for Loop : Collections and Immutability

Enhanced for loop was added in Java SE 1.5. It can be used with Arrays and collections to iterate item-wise/element-wise. It works like read data of very ancient programming language called BASIC... atleast to me it looks like that... You can define read element of the collection element type and do operations on data. The amazing part is whatever you do to the read element, it does not disturb the original collection, that is data in for loop is immutable...
package test;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.random;
/**
*
* @author nkan
*/
public class EnhancedForLoop {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
for (int i=0;i<5;i++){
intList.add((int) (random() * 100));
}

System.out.println("Added List elements : "+intList);
/* To perfomr element wise operation */
for(int x : intList){
x++;
System.out.println("x = "+x);
}
/* you have incremented x, may be you are thinking that ArrayList : intList has be modified */
System.out.println("List elements now : "+intList);
/* OOPs... it has not changed...But let us conform it once again by using enhanced for loop */
System.out.println("After Updation : incremented element list is : ");
for(int x : intList){
System.out.println("x = "+x);
}
}
}
When I executed this program :
Added List elements : [98, 14, 30, 34, 43]
x = 99
x = 15
x = 31
x = 35
x = 44
List elements now : [98, 14, 30, 34, 43]
After Updation : incremented element list is : 
x = 98
x = 14
x = 30
x = 34
x = 43

Created and posted by Nancy @ 12/17/2015 2:25 am

No comments:

Post a Comment