How to check the Java list size?

JavaObject Oriented ProgrammingProgramming

List provides a method size() to check the current size of the list.

Syntax

int size()

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Returns

The number of elements in this list.

Example

The following example shows how to get size of a list using size() method.

package com.tutorialspoint;

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());
      list.add(5);
      list.add(6);
      list.add(7);
      System.out.println("List: " + list);
      System.out.println("List Size: " + list.size());
      list.remove(5);
      System.out.println("List: " + list);
      System.out.println("List Size: " + list.size());
   }
}

Output

This will produce the following result −

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
raja
Updated on 09-May-2022 11:47:11

Advertisements