Skip to Content

Java ArrayList Example

  1. /*
  2.   Java ArrayList Example
  3.   This Java ArrayList Example shows how to create an object of Java ArrayList. It also
  4.   shows how to add elements to ArrayList and how get the same from ArrayList.
  5. */
  6.  
  7. import java.util.ArrayList;
  8.  
  9. public class SimpleArrayListExample {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create an ArrayList object
  14.     ArrayList arrayList = new ArrayList();
  15.    
  16.     /*
  17.        Add elements to Arraylist using
  18.        boolean add(Object o) method. It returns true as a general behavior
  19.        of Collection.add method. The specified object is appended at the end
  20.        of the ArrayList.
  21.     */
  22.     arrayList.add("1");
  23.     arrayList.add("2");
  24.     arrayList.add("3");
  25.    
  26.     /*
  27.       Use get method of Java ArrayList class to display elements of ArrayList.
  28.       Object get(int index) returns and element at the specified index in
  29.       the ArrayList    
  30.     */
  31.     System.out.println("Getting elements of ArrayList");
  32.     System.out.println(arrayList.get(0));
  33.     System.out.println(arrayList.get(1));
  34.     System.out.println(arrayList.get(2));
  35.   }
  36. }
  37.  
  38. /*
  39. Output would be
  40. Getting elements of ArrayList
  41. 1
  42. 2
  43. 3
  44. */