java

How to get the length or size of an ArrayList in Java

In this tutorial, we are going to see how to get the length or size of an ArrayList in Java. You can use size() method of java.util.ArrayList class to find the size of an ArrayList in Java. size() method returns the number of elements present in an ArrayList. It’s different from length() method which is used for arrays.

When you create an ArrayList object in Java without specifying the capacity, it is created with a default capacity of 10.

ArrayList is a dynamic array, it automatically resizes itself when the size (number of elements in the ArrayList) exceeds the limit. Additionally, when an ArrayList is first created, it’s empty and size() method returns zero. If you add elements, the size increases one by one. You can also remove all items from the ArrayList using the clear() method which will make the ArrayList empty again.
 

 

Java Program to get the length or size of an ArrayList:
import java.util.*; 
  
public class Main 
{ 
    public static void main(String args[]) 
    { 
        // Create and initialize the ArrayList
        List arr = new ArrayList();
        arr.add("A");
        arr.add("B");
        arr.add("C");
        arr.add("D");
        arr.add("E");

        // display the size of the ArrayList
        System.out.println("The size of the ArrayList is: "+ arr.size());
    }
}

Output:

The size of the ArrayList is: 5
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *