How to use List size() method in Java With Examples?

JavaObject Oriented ProgrammingProgramming

The List interface extends the Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, list allows duplicate elements, and allows multiple null values if null value is allowed in the list.

List interface size() can be used to get the count of elements currently present in the list. It always returns the count of currently present elements. You can check the latest size after adding/removing element(s) to the list.

Syntax

int size()

Notes

  • Returns the number of elements in this list.

  • If this list contains more than Integer.MAX_VALUE elements, then Integer.MAX_VALUE is returned as size.

Returns

The number of elements in this list.

Example 1

The following example shows how to check 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,5,6));
      System.out.println("List: " + list);
      System.out.println("List size: " + list.size());
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 4, 5, 6]
List size: 6

Example 2

The following example shows how to check size of a list using size() method after adding/removing elements −

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

Output

This will produce the following result −

List: [1, 2, 3, 4, 5, 6]
List size: 6
List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List size: 9
List: [1, 3, 4, 5, 6, 7, 8, 9]
List size: 8
raja
Updated on 27-May-2022 08:33:11

Advertisements