Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

ArrayList

In this tutorial we will discuss about the ArrayList which is a class available in java.util package and it a List type collection it means it implements java.util.List interface.

ArrayList important points:

1. It stores the elements in Added order.
2. It uses Index Representation to store their elements same as Array.
3. In ArrayList we can store the different types of data.
4. We can store the duplicate elements in an ArrayList.
5. We can traverse an ArrayList using Iterator and ListIterator.
6. ArrayList class methods are not synchronized in nature, so it doesn’t affect the concurrency of the Application.
7. Random Access is allowed in ArrayList.
8. An ArrayList is a eligible for Cloning and Serialization because java.util.ArratList class implements java.lang.Cloneable and java.util.Serializable interface.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      // ArrayList is storing the elements in added order.
      ArrayListal1 = newArrayList();
      al1.add(101);
      al1.add(102);
      al1.add(103);
      al1.add(104);
      al1.add(105);
      al1.add(101);
      System.out.println("al1 :- " + al1);
      // We are accessing the element of an ArrayList using their Index.
      System.out.println("---------------------------------");
      for (inti = 0; i <= al1.size() - 1; i++) {
         System.out.println("Index :- " + i + " | Value :- " + al1.get(i));
      }
      // Traversing ArrayList using Iterator :
      System.out.println("---------------------------------");
      Iteratoriterator = al1.iterator();
      while (iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
      System.out.println("\n---------------------------------");
      // Traversing ArrayList using List-Iterator :
      ListIteratorlistIterator = al1.listIterator();
      System.out.print("In Forward Order :- ");
      while (listIterator.hasNext()) {
         System.out.print(listIterator.next() + " ");
      }
      System.out.print("\nIn Reverse Order :- ");
      while (listIterator.hasPrevious()) {
         System.out.print(listIterator.previous() + " ");
      }
      System.out.println();
      // Creating Clone of ArrayList :
      ArrayListclone = (ArrayList) al1.clone();
      System.out.println("Original ArrayList :- " + al1);
      System.out.println("Clone ArrayList :- " + clone);
   }
}
    al1 :- [101, 102, 103, 104, 105, 101]
    ---------------------------------
    Index :- 0 | Value :- 101
    Index :- 1 | Value :- 102
    Index :- 2 | Value :- 103
    Index :- 3 | Value :- 104
    Index :- 4 | Value :- 105
    Index :- 5 | Value :- 101
    ---------------------------------
    101 102 103 104 105 101 
    ---------------------------------
    In Forward Order :- 101 102 103 104 105 101 
    In Reverse Order :- 101 105 104 103 102 101 
    Original ArrayList :- [101, 102, 103, 104, 105, 101]
    Clone ArrayList :- [101, 102, 103, 104, 105, 101]
            

In this example, we create an object of the java.util.ArrayList class, named al1, and store elements using the add() method. Subsequently, we print their values on the console. This illustrates that an ArrayList can store elements in the order they are added, allowing different types of values with duplicity.
In the second section, we retrieve values from the ArrayList al1 using the get() method, which operates based on indices.
In the third section, we create an Iterator using the iterator() method of the java.util.ArrayList class. We use hasNext() to check if the current ArrayList (al1) has more elements to iterate through. Simultaneously, we use next() to retrieve the next element.
In the third section, we create an Iterator using the iterator() method of the java.util.ArrayList class. We use hasNext() to check if the current ArrayList (al1) has more elements to iterate through. Simultaneously, we use next() to retrieve the next element.
Finally, in the last section, we create a clone of the existing ArrayList (al1) by invoking the clone() method of the ArrayList class and print its values.
In this example, we will explore how to work with a simple ArrayList.

Different Constructor of java.util.ArrayList class:

In java.util.ArrayList class we have 3 different constructors:

1. public java.util.ArrayList() : It creates an ArrayList object with the default capacity, which is 10.

2. public java.util.ArrayList(int) : This constructor is utilized to create an ArrayList with a custom capacity specified as an argument.

3. public java.util.ArrayList(java.util.Collection<? extends E>); : As we can see, the constructor contains a java.util.Collection type parameter. We use this constructor to create an ArrayList that includes all the elements from the specified collection.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      al1.add(101);
      al1.add(102);
      System.out.println("al1 :- " + al1);
      ArrayListal2 = newArrayList(al1);
      System.out.println("al2 :- " + al2);
   }
}
        
    al1 :- [101, 102]
    al2 :- [101, 102]
            
Important Method of java.util.ArrayList class:

1. public int size(): It returns the number of elements in the current working ArrayList.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      System.out.println("al1 :- " + al1);
      System.out.println("al1.size :- " + al1.size());
      al1.add(101);
      al1.add("Hello");
      al1.add(true);
      System.out.println("al1 :- " + al1);
      System.out.println("al1.size :- " + al1.size());
   }
}
        
    al1 :- []
    al1.size :- 0
    al1 :- [101, Hello, true]
    al1.size :- 3
            

2. public boolean add(E): It appends the elements to the end of the list.

3. public void add(int, E): It appends the element at the specified position in the current working list.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      for (inti = 1; i <= 10; i++) {
         al1.add(101 + i);
      }
      System.out.println("al1 :- " + al1);
      al1.add(5, "Hello");
      System.out.println("al1 :- " + al1);
   }
}
    al1 :- [102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    al1 :- [102, 103, 104, 105, 106, Hello, 107, 108, 109, 110, 111]
            

In this example we are working on a requirement and we will understand how we can override hashCode() of java.lang.Object class into a sub class. As per the current requirement we need hash code in a sequence at every invocation of hashCode() via Student class object whether the object is same or not.

4. public booleanaddAll(java.util.Collection<? extends E>) : This method is basically used to add all the elements of the specified Collection to the last position of the current working list.

5. public booleanaddAll(int, java.util.Collection<? extends E>) : This method is basically used to add all the elements of the specified Collection at the specified position of the current working list.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      for (inti = 1; i <= 10; i++) {
         al1.add(101 + i);
      }
      System.out.println("al1 :- " + al1);
      ArrayListal2 = newArrayList();
      al2.add("E1");
      al2.add("E2");
      al2.add("E3");
      System.out.println("al2 :- " + al2);
      al2.addAll(al1);
      System.out.println("al2 :- " + al2);
      ArrayListal3 = newArrayList();
      al3.add("E4");
      al3.add("E5");
      al3.add("E5");
      al2.addAll(6, al3);
      System.out.println("al2 :- " + al2);
   }
}
    al1 :- [102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    al2 :- [E1, E2, E3]
    al2 :- [E1, E2, E3, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    al2 :- [E1, E2, E3, 102, 103, 104, E4, E5, E5, 105, 106, 107, 108, 109, 110, 111]
            

6. public E remove(int): It removes the element from the specified position in the list, shifts the subsequent elements to the left, and returns the removed element. If we try to remove an element from an index that is not in the current list, we get an IndexOutOfBoundsException.

7. public boolean remove(java.lang.Object): It removes the elements from the list that we have passed as an argument at the time of method invocation and returns true; otherwise, it returns false.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      for (inti = 1; i <= 10; i++) {
         al1.add(101 + i);
      }
      System.out.println("al1 :- " + al1);
      System.out.println(al1.remove(4) + " removed.");
      System.out.println("al1 :- " + al1);
      // System.out.println(al1.remove(100)); :- IndexOutOfBoundsException
      System.out.println(al1.remove(newInteger(103)));
      System.out.println("al1 :- " + al1);
      System.out.println(al1.remove("JTC"));
      System.out.println("al1 :- " + al1);
   }
}
    al1 :- [102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    106 removed.
    al1 :- [102, 103, 104, 105, 107, 108, 109, 110, 111]
    true
    al1 :- [102, 104, 105, 107, 108, 109, 110, 111]
    false
    al1 :- [102, 104, 105, 107, 108, 109, 110, 111]
            

8. publicbooleanremoveAll(java.util.Collection<?>): It removes all the matching elements of the collection that we have passed as an argument from the current list and returns true; otherwise, it returns false.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      for (inti = 1; i <= 10; i++) {
         al1.add(101 + i);
      }
      System.out.println("al1 :- " + al1);
      ArrayListal2 = newArrayList();
      al2.add(101);
      al2.add(118);
      al2.add(109);
      System.out.println(al1.removeAll(al2));
      System.out.println("al1 :- " + al1);
   }
}
    al1 :- [102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    true
    al1 :- [102, 103, 104, 105, 106, 107, 108, 110, 111]
            

9. public java.lang.Object[] toArray(): It returns an array of type Object that contains all the elements of the current working ArrayList.

            
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      for (inti = 1; i <= 10; i++) {
         al1.add(101 + i);
      }
      System.out.println("al1 :- " + al1);
      Object ar1[] = al1.toArray();
      System.out.println("ar1 :- " + ar1);
      for (inti = 0; i <= ar1.length - 1; i++) {
         System.out.println("ar1[" + i + "] :- " + ar1[i]);
      }
   }
}
    al1 :- [102, 103, 104, 105, 106, 107, 108, 109, 110, 111]
    ar1 :- [Ljava.lang.Object;@515f550a
    ar1[0] :- 102
    ar1[1] :- 103
    ar1[2] :- 104
    ar1[3] :- 105
    ar1[4] :- 106
    ar1[5] :- 107
    ar1[6] :- 108
    ar1[7] :- 109
    ar1[8] :- 110
    ar1[9] :- 111
            

10. public void sort(java.util.Comparator<? super E>): Sorts this list according to the order induced by the specified Comparator. The sort is stable: this method must not reorder equal elements. All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). If the specified comparator is null, then all elements in this list must implement the Comparable interface, and the elements' natural ordering should be used. This list must be modifiable but need not be resizable.

            
importjava.util.ArrayList;
importjava.util.Comparator;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListal1 = newArrayList();
      al1.add(101);
      al1.add(102);
      al1.add(104);
      al1.add(103);
      al1.sort(Comparator.naturalOrder());
      System.out.println(al1);
      al1.sort(Comparator.reverseOrder());
      System.out.println(al1);
   }
}
    [101, 102, 103, 104]
    [104, 103, 102, 101]
            
Custom Sorting using sort method of java.util.ArrayList class:
            
importjava.util.ArrayList;
importjava.util.Comparator;
importjava.util.Iterator;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayList < Student > s1 = newArrayList < Student > ();
      s1.add(new Student(101, "Vivek", "Noida"));
      s1.add(new Student(102, "Amit", "Delhi"));
      s1.add(new Student(101, "Vivek", "Noida"));
      s1.add(new Student(100, "Neha", "Patna"));
      System.out.println("s1 :- " + s1);
      s1.sort(newMyCompare());
      System.out.println("s1 :- " + s1);
   }
}
classMyCompareimplements Comparator < Student > {
   @Override
   publicint compare(Student s1, Student s2) {
      if (s1.sid > s2.sid) {
         return 1;
      }
      elseif(s1.sid == s2.sid) {
         return 0;
      } else {
         return -1;
      }
   }
}
class Student {
   intsid;
   String sname;
   String scity;
   public Student(intsid, String sname, String scity) {
      this.sid = sid;
      this.sname = sname;
      this.scity = scity;
   }
   @Override
   public String toString() {
      return "Student [sid=" + sid + ", sname=" + sname + ", scity=" + scity + "]";
   }
}
    s1 :- [Student [sid=101, sname=Vivek, scity=Noida], Student [sid=102, sname=Amit, scity=Delhi], Student [sid=101, sname=Vivek, scity=Noida], Student [sid=100, sname=Neha, scity=Patna]]
    
    s1 :- [Student [sid=100, sname=Neha, scity=Patna], Student [sid=101, sname=Vivek, scity=Noida], Student [sid=101, sname=Vivek, scity=Noida], Student [sid=102, sname=Amit, scity=Delhi]]