Published Jan 27, 2023
Contribute to Docs

The .size() method of the ArrayList class returns the number of elements in the list.


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()


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 Strings
ArrayList<String> list = new ArrayList<>();
// Add some elements to the list
// Get the size of the list
int size = list.size();
// Print the size of the list
System.out.println("Size of list: " + size);

The output for the above code is:

Size of list: 3

All contributors

Looking to contribute?

Learn Java on Codecademy