Home‎ > ‎Applied Core Java‎ > ‎Collection Framework‎ > ‎

Test Array List

Problem : Create a dynamic array that can add any number of elements of any object.

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestArrayList.java  and copy below contents.

/*
 *
A program of array list.
 */

import java.util.*;

public class TestArrayList {

    public static void main(String[] args) {

        ArrayList v = new ArrayList();

        //You can insert any object in the ArrayList. Here it is string

        v.add("Ram");

        v.add("Shyam");
        v.add("Balram");

                   //Return type of get() method is Object.

        Object o = v.get(0);

        //You can insert any object in the ArrayList. Here it is Integer
        //Primitive data type need to be converted into Objects before inserting.
        Integer i = new Integer(5);
        v.add(i);

                    //Type cast your object in desired Class
        Integer value = (Integer) v.get(3);
        System.out.println("3 value is " + value);


                   //Get all elements and print

        System.out.println("Print All Elements with help of For loop ");

        for (int j = 0; j < v.size(); j++) {
            System.out.println(j + " : " + v.get(j));
        }
       
        //Get all elements and print with help of Iterator interface
        Iterator it = v.iterator(); //Get an iterator

        System.out.println("Print All Elements with help of Iterator ");

        while(it.hasNext()){ //Checks if any element in list
            Object oo = it.next(); //Get next available element
            System.out.println(" From Iterator -- " +oo);
        }
       
    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestArrayList.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestArrayList.java with help of 
    • javac TestArrayList.java command. Command will create class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestArrayList command.

Output

C:\sunilos>java TestArrayList
Value of Index # 3 = 5
Print All Elements with help of For loop
0 : Ram
1 : Shyam
2 : Balram
3 : 5
Print All Elements with help of Iterator
 From Iterator -- Ram
 From Iterator -- Shyam
 From Iterator -- Balram
 From Iterator -- 5


<<Previous | Next>>
ċ
TestArrayList.java
(1k)
nakul shukla,
Mar 31, 2009, 12:22 AM
Comments