Java .size()
Published Jan 27, 2023
Contribute to Docs
The .size() method of the ArrayList class returns the number of elements in the list.
Syntax
Here, a variable size of type int is initialized with the size of a list. The List interface is an ordered collection of elements and is implemented by various classes such as ArrayList, LinkedList, and Vector:
int size = list.size()
Example
The following example creates an ArrayList, uses .add() to append elements to it, and uses .size() to print out its size:
import java.util.ArrayList;public class Main {public static void main(String[] args) {// Create an ArrayList of StringsArrayList<String> list = new ArrayList<>();// Add some elements to the listlist.add("Apple");list.add("Banana");list.add("Orange");// Get the size of the listint size = list.size();// Print the size of the listSystem.out.println("Size of list: " + size);}}
The output for the above code is:
Size of list: 3
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours