Tuesday, October 2, 2012

Difference between Standard Arrays and ArrayList ?

import java.util.*;
public class StandardArrays_Vs_ArrayList {

    public static void main(String[] args) {
        /*
        We Cannot Define it this [] (i.e) we cannot give any empty declaration, declaring such will

        throw an CompiletimeException we have to start the declaration Starting from Numeric 
        Value 1, (i.e) we cannot declare as new String[0] as it will throw an RuntimeException
        String []array = new String[];
       
*/
        String []array = new String[1];
        array[0] = "0";
        System.out.println("String []array " + array[0]);
       
        /*
        The below programme proves that an ArrayList grows dynamically...
       
*/
        ArrayList a1 = new ArrayList();
        a1.add("One");
        /*
        ... as you can see here the ArrayList size has not been specified and the ArrayList size is 

        now 1
       
*/
        System.out.println("The Initial Size is " + a1.size());
        a1.add("Two");
        a1.add("Three");
        /*
        and here after adding 2 records the ArrayList size increases to 3.it can keep increasing to 

        the point of when there is an OutOfMemoryError due to insufficient heapspace.
       
*/
        System.out.println("Now The Size is " + a1.size());
    }

}

No comments:

Post a Comment