Monday, January 14, 2013

ArrayLists

ArrayList( )
The first constructor builds an empty array list.
ArrayList(collection c)
The second constructor builds an array list initialized with elements of collection c.
ArrayList(int capacity)
The third constructor builds an array list that has an initial capacity.

Objects of type String are added to it.

import java.util.*;
class ArrayListDemo
{

public static void main(String args[])

{

ArrayList al = new ArrayList(); // creates new array list
System.out.println("Size of al: " + al.size()); // prints size of array list

al.add("A");
al.add("B");
al.add("C"); // adds elements to array list
al.add(1, "A2"); // adds A2 (index 1) to the array list while shifting other elements over

System.out.println("Size of al after additions: " + al.size()); // prints size of array list

System.out.println("Contents of al: " + al); // prints elements of array list

al.remove("C"); removes C from array list
al.remove(2); // removes element (index 2) from array list

System.out.println("Size of al after deletions: " + al.size()); // prints size of array list
System.out.println("Contents of al: " + al); // prints elements of array list

}
}

Output:
Size of al: 0
Size of al after additions: 4
Contents of al: [A, A2, B, C]
Size of al after deletions: 2
Contents of al: [A, A2]

No comments:

Post a Comment