How do I set the size of a list in Java?


Java list size is dynamic. It increases automatically whenever you add an element to it and this operation exceeds the initial capacity. You can define the initial capacity at the time of list creation so that it allocates memory after initial capacity exhausts.

List<Integer> list = new ArrayList<Integer>(10);

But please don't use index > 0 to add element, otherwise you will get IndexOutOfBoundsException as the index will out of range considering size is 0 and index > size().

List provides size() method to get the count of the elements present in 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.

Example

Following is the example showing the usage of 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));
      System.out.println("List: " + list);
      System.out.println("List size: " + list.size());
      list.add(4);
      list.add(5);
      list.add(6);
      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]
List size: 3
List: [1, 2, 3, 4, 5, 6]
List size: 6
List: [1, 3, 4, 5, 6]
List size: 5

Updated on: 10-May-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements