ArrayList:
The arraylist class provides dynamic arrays for storing elements. It extends AbstractList class and implements List interface. It stores only one type of objects (generic array).
Syntax:
ArrayList<String> arr=new ArrayList<String>(); // store string objects in the arraylist
ArrayList can grow and shrink as per the need means there is no wastage of memory. To add an element we use add() method and to remove an element we use remove() method. We can iterate ArrayList elements using either for each loop or by the iterator provided by the Collection Framewok.
Example:
import java.util.*;
public class ArrayList1 {
public static void main(String args[]) {
// create an array list
ArrayList arr = new ArrayList();
System.out.println("Initial size of arr: " + arr.size());
// add elements to the array list
arr.add("C");
arr.add("A");
arr.add("E");
arr.add("B");
arr.add("D");
arr.add("F");
arr.add(1, "M");
System.out.println("after inserting elements: " + arr.size());
// display the array list
System.out.println("Contents of arr: " + arr);
// Delete elements from array list
arr.remove("F");
arr.remove(2);
System.out.println(" after deleting elements: " + arr.size());
System.out.println("Contents of arr: " + arr);
}
}
Output:
Initial size of arr: 0
after inserting elements: 7
Contents of arr: [C, M, A, E, B, D, F]
after deleting elements: 5
Contents of arr: [C, M, E, B, D]
0 Comment(s)