by Dinesh Thakur Category: Classes

Java ArrayList class is a part of unified architecture (collection framework) interfaces are present in java.util package and used when we want to change the array size when your Java program run. You know that arrays are that they're fixed size that must be specified the number of elements when the array created. How to add elements values to an array in java that filled? It's an easy way to create a more extensive array, and all its elements are copied from the (smaller) source array to the (broader) target array, with the remaining space for new elements. It's an alternative is to use the ArrayList whose size can change frequently. An instance of Java ArrayList class contains an array that dynamically increased as required so that it relaxes the programmer from the burden of doing this.

Following are few key points to note about ArrayList in Java

• The ArrayList class inherits AbstractList class and implements the List interface.

• Java ArrayList provides automatic resizing , also called a dynamic array; It expands as you add more elements or shrink if elements removed.

• Java ArrayList class retrieve a random element from the list.

• The ArrayList class allows duplicate and null values.

• The ArrayList class is just like arrays, It retrieves the elements by their index.

• The ArrayList class cannot use for primitive types, like int, char. We need a wrapper class for such cases.

• Java ArrayList class can see as similar to vector in C++.

Java ArrayList class

Below are some of the constructors and methods in this class.

ArrayList(): Constructor creates an empty array of size ten.
ArrayList(int n): Constructor creates an empty array of size n.
Boolean add (Object obj): Adds the object obj to the end of the array and returns true.
Object remove(int index): Removes and returns the object at the given index.
Int size(): Returns the number of elements in this array.
Boolean isEmpty(): Returns true if this array does not have any elements; otherwise, returns false.
Object get (int i): Returns (without removing) the element at index i from the array.
Object set(int i, Object obj): Changes the element at index i to obj and returns the previous element at this index.
forEach(Consumer<? super T> action): performs the given action for each element of this stream. The forEach() method added to the Iterable interface.
retainAll?(Collection c): Remove its elements from a list that not contained in the specified collection.
removeIf?(Predicate filter): Removes all of the elements from the List that satisfy the given predicate.
contains?(Object o): Returns true if this list contains the specified element.
remove?(int index): Removes the element at the specified index from a list.
remove(Object o): removes the first occurrence of the specified object from the list.
get?(int index): get the element of the specified position within the list.
subList?(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

spliterator?(): Creates a late-binding and fail-fast Spliterator over the elements in this list.
set?(int index, E element): Replaces the element at the specified position in this list with the specified element.
size?(): Returns the number of elements in this list.
removeAll?(Collection c): Removes from this list all of its elements that are contained in the specified collection.
ensureCapacity?(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
listIterator?(): Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index): Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
isEmpty?(): The isEmpty() method is returns true if this list is empty.
removeRange?(int fromIndex, int toIndex): The removeRange() method is used to removes all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive from a ArrayList object.
Void clear(): The clear() method is used to remove all the elements from a list.
Void add(int index, Object element): This method is used to insert a specific element at a specific index in a ArrayList object.
Void trimToSize(): This method is used to trim a ArrayList instance to the list’s current size.
Int indexOf(Object O): The index the first occurrence of an element in an ArrayList object.
Int lastIndexOf(Object O): This method is used to get the index of the last occurrence of a specific element is either returned or -1 in an ArrayList object.
Object clone(): The clone() method is used to return a shallow copy of an existing ArrayList object.
Object[] toArray(Object[] O): The toArray() method is used to return an array containing all of the elements in this ArrayList object in the correct order (from first to the last element).
Boolean addAll(Collection C): This method used to add all the elements from a specific collection to another list.
Boolean add(Object o): The add(Object o) method used to add a specified element to the ArrayList.
Boolean addAll(int index, Collection C): used for adding all of the elements of Collection c starting at the specified position from a specific collection into the end of the list.

How to create an ArrayList and Add new elements

This example shows:

Create a List using theArrayList()constructor.

Add new elements to the List using theadd()method.

import java.util.ArrayList;
import java.util.List;
public class ArrayListEx {
     public static void main(String[] args) {
            // Creating an ArrayList of String
         List<String> state = new ArrayList<>();
            // Adding new elements to the ArrayList
          state.add("Punjab");
          state.add("UP");
          state.add("Rajasthan");
          state.add("J & K");
          System.out.println(state);
            // Adding an element at a particular index in an ArrayList
            state.add(3,"Himachal");
          System.out.println(state);
     }
}

[Punjab, UP, Rajasthan, J & K]
[Punjab, UP, Rajasthan, Himachal, J & K]

How to create an ArrayList from another collection

This example shows:

Create a List from another collection using theArrayList(Collection c)constructor.

Add all the elements from an existing collection to the new the List using theaddAll()method.

import java.util.ArrayList;
import java.util.List;
public class ArrayListFromCollection {
      public static void main(String[] args) {
           List<String> Birds =newArrayList<>();
           Birds.add("Crow");
           Birds.add("Peacock");
           Birds.add("Sparrow");
           Birds.add("Ostrich");
           Birds.add("Pigeon");
                // Creating an ArrayList from another collection
           List<String> BirdsandAnimals = newArrayList<>(Birds);
           List<String> Animals = newArrayList<>();
           Animals.add("Dog");
           Animals.add("Puppy");
           Animals.add("Turtle");
           Animals.add("Rabbit");
           Animals.add("Parrot");
           // Adding an entire collection to an ArrayList
          BirdsandAnimals.addAll(Animals);
          System.out.println(BirdsandAnimals);
      }
}

[Crow, Peacock, Sparrow, Ostrich, Pigeon, Dog, Puppy, Turtle, Rabbit, Parrot]

How to accessing elements from an ArrayList

This example shows:

• For checking if an ArrayList is empty or not using the isEmpty() method.
• Check the size of an ArrayList using the size() method.
• Access element of an index in an ArrayList using the get() method.
• Modify the element of an index in an ArrayList using the set() method.

import java.util.ArrayList;
import java.util.List;
public class AccessElementsFromArrayList {
      public static void main(String[] args){
           List<String> continents =newArrayList<>();
           // Check if an ArrayList is empty
           System.out.println("Is the continents list empty? : "+ continents.isEmpty());
           continents.add("Asia");
           continents.add("Africa");
           continents.add("Europe");
           continents.add("Australia");
           continents.add("North America");

           continents.add("South America");

           continents.add("Antarctica");
          // Find the size of an ArrayList
       System.out.println("Here are the top "+ continents.size()+" is the world's largest continent of the seven continents in size and population.");
          System.out.println(continents);
          // Retrieve the element at a given index
          String largestcontinent = continents.get(0);
          String secondlargest = continents.get(1);
          String smallestcontinent = continents.get(continents.size()-4);
          System.out.println("World's largest continent: "+ largestcontinent);
          System.out.println("Second largest: "+ secondlargest);
          System.out.println("World's smallest continent: "+ smallestcontinent);
          // Modify the element at a given index
          continents.set(3,"island continent");
          System.out.println("Modified seven continents list: "+ continents);
      }
}

Is the continents list empty? : true
Here are the top 7 is the world's largest continent of the seven continents in size and population.
[Asia, Africa, Europe, Australia, North America, South America, Antarctica]
World's largest continent: Asia
Second largest: Africa
World's smallest continent: Australia
Modified seven continents list: [Asia, Africa, Europe, island continent, North America, South America, Antarctica]

How to remove the elements from an ArrayList

This example shows:

• Removes the element at the specified index from a list | remove(int index)
• removes the first occurrence of the specified object from the list. | remove(Object o)
• Removes from this list all of its elements that are contained in the specified collection. | removeAll()
• Removes all of the elements from the List that satisfy the given predicate. | removeIf()
• The clear() method is used to remove all the elements from a list. | clear()

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class RemoveObjectsFromArrayList {
      public static void main(String[] args){
              List<String> StudentName =newArrayList<>();
              StudentName.add("Manjinder");
              StudentName.add("Karan");
              StudentName.add("Sunil");
              StudentName.add("Rajwinder");
              StudentName.add("Pankaj");
              StudentName.add("Punar");
              StudentName.add("Sandeep");
              System.out.println("Student List: "+ StudentName);
             // Remove the element at index `5`
              StudentName.remove(5);
              System.out.println("After remove(5): "+ StudentName);
              // Remove the first occurrence of the given element from the ArrayList
              // (The remove() method returns false if the element does not exist in the ArrayList)
              boolean isRemoved = StudentName.remove("Rajwinder");
              System.out.println("After remove(\"Rajwinder\"): "+ StudentName);
             // Remove all the elements that exist in a given collection
             List<String> Removeallelements =newArrayList<>();
             Removeallelements.add("Pankaj");
             Removeallelements.add("Punar");
             Removeallelements.add("Sandeep");
             StudentName.removeAll(Removeallelements);
             System.out.println("After removeAll(Removeallelements): "+ StudentName);
            // Remove all the elements that satisfy the given predicate
            StudentName.removeIf(new Predicate<String>(){
                 @Overridepublicboolean test(String s){
                     return s.startsWith("S");
                 }
            });
             /*  The above removeIf() call can also be written using lambda
             expression like this -
            
             StudentName.removeIf(s -> s.startsWith("S"))
        */
             System.out.println("After Removing all elements that start with \"S\": "+ StudentName);
            // Remove all elements from the ArrayList
            StudentName.clear();
            System.out.println("After clear(): "+ StudentName);
        }
}

Student List: [Manjinder, Karan, Sunil, Rajwinder, Pankaj, Punar, Sandeep]
After remove(5): [Manjinder, Karan, Sunil, Rajwinder, Pankaj, Sandeep]
After remove("Rajwinder"): [Manjinder, Karan, Sunil, Pankaj, Sandeep]
After removeAll(Removeallelements): [Manjinder, Karan, Sunil]
After Removing all elements that start with "S": [Manjinder, Karan]
After clear(): []

Iterating over an ArrayList in java

There are various example shows how to iterate over an ArrayList in java

• forEach() method.
• iterator().
• forEachRemaining() method.
• listIterator().
• for-each loop.
• for loop.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ArrayListelements {
        public static void main(String[] args){
           List<String> tvSerials =newArrayList<>();
           tvSerials.add("Tarak Mehta ka Ulta Chasma");
           tvSerials.add("Tenali Rama");
           tvSerials.add("Kumkum");
           tvSerials.add("CID");
           System.out.println("=== Iterate using Java 8 forEach");
           tvSerials.forEach(tvSerial ->{
               System.out.println(tvSerial);
           });
           System.out.println("\n=== Iterate using an iterator() ===");
           Iterator<String> tvSerialIterator = tvSerials.iterator();
           while(tvSerialIterator.hasNext()){
               String tvSerial = tvSerialIterator.next();
               System.out.println(tvSerial);
           }
           System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ===");
           tvSerialIterator = tvSerials.iterator();
           tvSerialIterator.forEachRemaining(tvSerial ->{
                 System.out.println(tvSerial);
           });
           System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ===");
           // Here, we start from the end of the list and traverse backwards.
           ListIterator<String> tvSerialListIterator = tvSerials.listIterator(tvSerials.size());
           while(tvSerialListIterator.hasPrevious()){
               String tvSerial = tvSerialListIterator.previous();
               System.out.println(tvSerial);
           }
           System.out.println("\n=== Iterate using simple for-each loop ===");
           for(String tvSerial: tvSerials){
                System.out.println(tvSerial);
           }
           System.out.println("\n=== Iterate using for loop with index ===");
           for(int i =0; i < tvSerials.size(); i++){
                 System.out.println(tvSerials.get(i));
            }
      }
}

=== Iterate using Java 8 forEach
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using an iterator() ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using an iterator() and Java 8 forEachRemaining() method ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using a listIterator() to traverse in both directions ===
CID
Kumkum
Tenali Rama
Tarak Mehta ka Ulta Chasma

=== Iterate using simple for-each loop ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

=== Iterate using for loop with index ===
Tarak Mehta ka Ulta Chasma
Tenali Rama
Kumkum
CID

How to Search an elements in an ArrayList

The example below shows

• Returns true if this list contains the specified element. | contains()
• The index the first occurrence of an element in an ArrayList object. | indexOf()
• This method is used to get the index of the last occurrence of a specific element is either returned or -1 in an ArrayList object. | lastIndexOf()

import java.util.ArrayList;
import
java.util.List;
public class SearchElements {
      public static void main(String[] args){
          List<String> EmployeeName =newArrayList<>();
          EmployeeName.add("Rajan");
          EmployeeName.add("Punar");
          EmployeeName.add("Sandeep");
          EmployeeName.add("Rohit");
          EmployeeName.add("Daljeet");
          EmployeeName.add("Raguveer");
          EmployeeName.add("Mukesh");
          // Check if an ArrayList contains a given element
          System.out.println("Does Employee Name array contain \"Rohit\"? : "+ EmployeeName.contains("Rohit"));
          // Find the index of the first occurrence of an element in an ArrayList
          System.out.println("indexOf \"Daljeet\": "+ EmployeeName.indexOf("Daljeet"));
          System.out.println("indexOf \"Renu\": "+ EmployeeName.indexOf("Renu"));
          // Find the index of the last occurrence of an element in an ArrayList
          System.out.println("lastIndexOf \"Raguveer\" : "+ EmployeeName.lastIndexOf("Raguveer"));
          System.out.println("lastIndexOf \"Billa\" : "+ EmployeeName.lastIndexOf("Billa"));
      }
}

Does Employee Name array contain "Rohit"? : true
indexOf "Daljeet": 4
indexOf "Renu": -1
lastIndexOf "Raguveer" : 5
lastIndexOf "Billa" : -1

How to create an ArrayList of user defined objects

Below is the example of, how to create an ArrayList of user defined objects

import java.util.ArrayList;
import java.util.List;
class User {
       private String Ename;
       private int Salary;
       public User(String Ename, int Salary) {
           this.Ename = Ename;
           this
.Salary = Salary;
       }
       public String getEname() {
           return Ename;
       }
       public void setEname(String Ename) {
           this.Ename = Ename;
       }
       public int getSalary() {
            return Salary;
       }
       public void setSalary(int Salary) {
           this.Salary = Salary;
       }
}
public class ArrListUDO {
        public static void main(String[] args) {
             List<User> users = new ArrayList<>();
             users.add(new User("Punardeep", 250000));
             users.add(new User("Sandeep", 460000));
             users.add(new User("Rohit", 550000));
             users.forEach(user -> {
                  System.out.println("Name : " + user.getEname() + ", Salary : " + user.getSalary());       

             });
        }
}

Name : Punardeep, Salary : 250000
Name : Sandeep, Salary : 460000
Name : Rohit, Salary : 550000





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles