ArrayList size() Method in Java

Published by user on

ArrayList size() method returns the number of elements in this list.
Syntax:

public int size()

Returns – number of elements in the ArrayList.

ArrayList Size Example

The below program shows how to use the size() method to check the number of elements in the list.

import java.util.ArrayList;

public class ArrayListSizeExample {
        public static void main(String[] args) {
                ArrayList numbers = new ArrayList<>();
                numbers.add(11);
                numbers.add(17);
                numbers.add(32);
                numbers.add(25);
                numbers.add(80);

                System.out.println("ArrayList element : " + numbers);
                System.out.println("Number of elements in the arraylist : " + numbers.size());
        }
}

Output:

ArrayList element : [11, 17, 32, 25, 80]
Number of elements in the arraylist : 5

Size Example with User-Defined Object

Here Employee objects are added to ArrayList.

class Employee {
        private int employeeId;
        private String employeeName;

        public Employee() {
        }

        public Employee(int employeeId, String employeeName) {
                super();
                this.employeeId = employeeId;
                this.employeeName = employeeName;
        }

        @Override
        public String toString() {
                return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
        }
}
import java.util.ArrayList;

public class ArrayListSizeDemo {

        public static void main(String[] args) {
                ArrayList employees = new ArrayList<>();
                employees.add(new Employee(101, "Ricky"));
                employees.add(new Employee(102, "Adam"));
                employees.add(new Employee(103, "Jhon"));
                employees.add(new Employee(104, "Chris"));

                System.out.println("ArrayList elements: ");
                for (Employee employee : employees) {
                        System.out.println(employee);
                }
                System.out.println("Number of elements in the arraylist: " + employees.size());

        }
}

Output:

ArrayList elements: 
Employee [employeeId=101, employeeName=Ricky]
Employee [employeeId=102, employeeName=Adam]
Employee [employeeId=103, employeeName=Jhon]
Employee [employeeId=104, employeeName=Chris]
Number of elements in the arraylist: 4

That’s all about the size() method of ArrayList in Java. Please share this article if you like it.

Further References:

ArrayList Documentation.

Categories: Java