Saturday 31 December 2011

Java Array List

ArrayList holds array of elements. In situations you may not know the actual size of the array, in that case the collection frame work has Array List. Its size increases dynamically as you add or delete the elements in the array. The elements in ArrayList are not sorted.
Class name:  ArrayList.java
import java.util.*;

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

              // Creating an object of arrayList
              List<Integer> num = new ArrayList<Integer>();

              // adding elements to list
              num.add(6);
              num.add(3);
              num.add(1);
              num.add(4);
              num.add(5);
              num.add(2);
              System.out.println("Contents of num: " + num);
             
              //Change value of num at position 1
              num.add(1, 7);
             
              // After changing num value at position 1
              System.out.println("Size of num after addition: " + num.size());
              System.out.println("Contents of num after addition: " + num);
             
              // Removing elements from list
              num.remove(6);
              num.remove(2);
              System.out.println("Final size of num after deletion: " + num.size());
              System.out.println("Contents of num after deletion: " + num);
       }
}

OUTPUT:
Contents of num: [6, 3, 1, 4, 5, 2]
Size of num after addition: 7
Contents of num after addition: [6, 7, 3, 1, 4, 5, 2]
Final size of num after deletion: 5
Contents of num after deletion: [6, 7, 1, 4, 5]

No comments:

Post a Comment