Collections Enhanced new for loop

Collections Enhanced new for loop


This is the second tutorial on the enhanced for loop on collections. Earlier one is with arrays – Arrays Enhanced for loop (foreach).

Collections Enhanced new for loop

Observe the following program.

Collections Enhanced new for loop

A generic ArrayList al1 that stores int values and al2 storing string values are created and elements are added.

Make a note, the data type stored by array list and the variable in the for loop are the same.

Collections Enhanced new for loop with Objects

Generics store only one type of data like all integers or all doubles or all Student objects etc. To store all types of objects like integers, doubles, Dates, Employees, a generic type Object can be taken as every object can be converted into the super-most class object Object.

To store any object, the loop can be modified as follows.

Collections Enhanced new for loop

Every object of Integer, Double, Date and String are stored in obj1. In each iteration, obj1 is printed.

2 thoughts on “Collections Enhanced new for loop

  1. sanjay

    import java.util.*;
    class ArrayListTest
    {
    public static void main(String… s)
    {
    ArrayList al=new ArrayList();
    al.add(“amit”);
    al.add(“deepak”);
    al.add(“Rahul”);
    al.add(“Sanjay”);
    al.add(“Sachin”);
    al.add(“rahul”);
    al.add(new Integer(110));
    Iterator itr=al.iterator();
    while(itr.hasNext())
    {
    Object ob=itr.next();
    String str=(String)ob;
    System.out.println(str);
    }
    }
    }
    sir ismae ClassCast exception aa rhi hai but why ?

Leave a Reply

Your email address will not be published. Required fields are marked *