Wednesday, 1 October 2014

Java : Collection Framework : ArrayList (Foreach and Iterator)
























Click here to watch in Youtube : https://www.youtube.com/watch?v=-OOfahFdLc4

ArrayListExample.java
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample
{

    public static void main(String[] args)
    {
        List<String> list = new ArrayList<String>();

        list.add("Ram");
        list.add("Dave");
        list.add("Peter");
        list.add("John");

        System.out.println(list);
    }

}

Output
[Ram, Dave, Peter, John]

ArrayListForEachExample.java
import java.util.ArrayList;
import java.util.List;

public class ArrayListForEachExample
{

    public static void main( String[] args )
    {
        List<String> list = new ArrayList<String>();

        list.add("Ram");
        list.add("Dave");
        list.add("Peter");
        list.add("John");

        /*
         * Using for-each loop getting each element from the list.
         */

        for( String name : list )
        {
            System.out.println(name);
        }

    }

}

Ouput
Ram
Dave
Peter
John

ArrayListForLoopIteratorExample.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListForLoopIteratorExample
{

    public static void main( String[] args )
    {
        List<String> list = new ArrayList<String>();

        list.add("Ram");
        list.add("Dave");
        list.add("Peter");
        list.add("John");

        /*
         * Using Iterator to get each element from the list.
         */

        for( Iterator<String> iterator = list.iterator(); iterator.hasNext(); )
        {
            String name = iterator.next();
            System.out.println(name);
        }

    }

}

Output
Ram
Dave
Peter
John

ArrayListWhileLoopIteratorExample.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListWhileLoopIteratorExample
{

    public static void main( String[] args )
    {
        List<String> list = new ArrayList<String>();

        list.add("Ram");
        list.add("Dave");
        list.add("Peter");
        list.add("John");

        Iterator<String> iterator = list.iterator();

        /*
         * Using Iterator to get each element from the list.
         */
        while( iterator.hasNext() )
        {
            String name = iterator.next();
            System.out.println(name);
        }

    }

}

Output
Ram
Dave
Peter
John

To Download ArrayListDemoSimple Project Click the below link

https://sites.google.com/site/javaee4321/java-collections/ArrayListDemoSimple.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge