
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the Size of an ArrayList in Java
In this article, we will learn to get the size of an ArrayList in Java. In Java, an ArrayList is a resizable array implementation of the List interface. Unlike arrays, which have a fixed length, an ArrayList dynamically grows as elements are added.
Using the size() Method
The size of an ArrayList can be obtained by using the java.util.ArrayList.size() method as it returns the number of elements in the ArrayList i.e. the size.
Syntax
int size = arrayList.size();
Getting the Size of an ArrayList
Following are the steps to get the size of an ArrayList using the size() method ?
- Start by importing the ArrayList and List classes from java.util package, allowing us to work with dynamic lists.
- Next, create an ArrayList by declaring aList as a List reference and initializing it as an ArrayList.
- Then add five elements using the add() method.
- Finally, use the size() method to check and retrieve the total number of elements present in the list.
Example
A program that demonstrates this is given as follows ?
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The size of the ArrayList is: " + aList.size()); } }
Output
The size of the ArrayList is: 5
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.size() returns the size of the ArrayList and that is displayed. A code snippet which demonstrates this is as follows ?
List aList = new ArrayList(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The size of the ArrayList is: " + aList.size());
Time Complexity: O(1), constant time, as size() simply returns an internal counter.
Space Complexity: O(1), no additional space is used; it only accesses a stored value.
Conclusion
The size() method is a simple and effective way to check how many elements are present in an ArrayList. Since ArrayList grows dynamically, keeping track of its size is crucial when iterating over elements or applying operations.