Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check the Java list size?
The Java List interface provides a size() method to check the current number of elements in the list. The size updates automatically as elements are added or removed.
Syntax
int size()
Returns the number of elements in the list. If the list contains more than Integer.MAX_VALUE elements, it returns Integer.MAX_VALUE.
Example
The following example shows how the list size changes after adding and removing elements ?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
System.out.println("List: " + list);
System.out.println("List Size: " + list.size());
// Add elements
list.add(5);
list.add(6);
list.add(7);
System.out.println("List: " + list);
System.out.println("List Size: " + list.size());
// Remove element at index 5 (value 6)
list.remove(5);
System.out.println("List: " + list);
System.out.println("List Size: " + list.size());
}
}
The output of the above code is ?
List: [1, 2, 3, 4] List Size: 4 List: [1, 2, 3, 4, 5, 6, 7] List Size: 7 List: [1, 2, 3, 4, 5, 7] List Size: 6
Conclusion
Use list.size() to get the current number of elements in any Java List. The size reflects the actual element count and updates dynamically as elements are added or removed. To check if a list is empty, you can also use list.isEmpty() which is equivalent to list.size() == 0.
Advertisements
