Posts Tagged ‘design patterns’

ArrayList and Iterator example

Here I want to share with you, the ArrayList and Iterator example. ArrayList is present in util package( java.util.ArrayList) means that we have to import before using it in our program. (import java.util.ArrayList) same as the case with Iterator too (import java.util.Iterator).

ArrayList and Iterator come very handy when we are dealing with a very big projects. Instead using static arrays we can easily, dynamically, create an array as a list and add reference of the elements to that. ArrayList can only take reference of the objects( I mean that we cannot give double, float or int as a reference instead we can use Wrapper classes such as Integer Double etc.,)

ArrayList class provides methods for basic array operations:

  • add( Object o ) – puts reference to object into ArrayList
  • get( int index ) – retrieves object reference from ArrayList index position
  • size() – returns ArrayList size
  • remove( int index ) – removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) – finds the index in this list of the first occurrence of the specified element
  • clear() – removes all of the elements

Example program:

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

 * @author Vasanth Raja Chittampally
public class Main {

     * @param args the command line arguments
    public static void main(String[] args) {
        ArrayList al = new ArrayList(20); //Exactly equal to ArrayList  al = new ArrayList(20)
        for (int i = 0; i < 20; i++) {
        Iterator i=al.iterator();

        while(i.hasNext()) {
        System.out.println("In the second iteration");
        Iterator i1=al.iterator();
         while(i1.hasNext()) {



If we don’t provide any size in ArrayList al = new ArrayList(); it takes 10 as ArrayList size. Here in the above program Iterator takes the ArrayList and iterates from starting to ending in a forward direction. Ouput: it prints 0 to 19 two times. ArrayLists cannot work with the multiple threads.. Click here to read my previous post talking about the synchronization of ArrayList


My Presentation on Design Patterns

Today I presented a topic on the composition design pattern. I thank all those who praised my presentation. I really thank Biju R Mohan sir for his remark of  “Excellent presentation, he made concept clear and easy to understand”. Here is my Software Architecture Composite Talk