Arraylist iteration in java

Arraylist:

Arraylist is used to hold any number of elements.

Program:

[java]
package com.ngdeveloper.com;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIteration {
public static void main(String[] args) {

// Arraylist which holds only string.
ArrayList<String> al = new ArrayList<String>();

//Adding below companies names to arraylist.
al.add("Hp");
al.add("Samsung");
al.add("Dell");
al.add("Apple");
al.add("Compaq");

//Iterator
Iterator iter = al.iterator();

//Iterating arraylist using while loop.

while(iter.hasNext()){
System.out.println("ArrayList Iteration using while loop "+iter.next());
}

//Iterating arraylist using foreach
for (String string : al) {
System.out.println("ArrayList Iteration using foreach loop "+string);
}

//Iterating arraylist using for loop.
for (String string : al) {
System.out.println("ArrayList Iteration using for loop "+string);
}
}
}
[/java]

Output:

ArrayList Iteration using while loop Hp
ArrayList Iteration using while loop Samsung
ArrayList Iteration using while loop Dell
ArrayList Iteration using while loop Apple
ArrayList Iteration using while loop Compaq
ArrayList Iteration using foreach loop Hp
ArrayList Iteration using foreach loop Samsung
ArrayList Iteration using foreach loop Dell
ArrayList Iteration using foreach loop Apple
ArrayList Iteration using foreach loop Compaq
ArrayList Iteration using for loop Hp
ArrayList Iteration using for loop Samsung
ArrayList Iteration using for loop Dell
ArrayList Iteration using for loop Apple
ArrayList Iteration using for loop Compaq

Thanks for reading this post………………!!!

One comment

  • azlina

    hiii ^_^,

    im trying to use your concept to apply on mine but with a bit twist… im trying to insert record using jsp which iterate with services in a simple word…submit form using spring MVC. the great news is i have succeed to insert the record but when i check on my sql yog i found that if i insert 2 records once in db it have like this >>
    id |sensortipid | type | commands | value | >>>>>>> field name in sql yog
    1 123 mote turn on 1
    2 123 mote turn of 0 >>>>>>> this is suppost to be..if i insert 2 records once it must insert as above..but what happen was…
    id |sensortipid | type | commands | value | >>>>>>> field name in sql yog
    1 123 mote,mote,,,, turn on, turn of,,, 1,0,,,, >>>>>>> this is happen..it does not saved in a new row but saved with a comma in my db…this is not supposed to happen..please do help me…im pretty sure that i need to do looping..but i do not know how…

Leave a Reply