Home > Java > javaTutorial > body text

In Java, how to set the size of a list?

PHPz
Release: 2023-08-27 10:01:06
forward
1285 people have browsed it

In Java, how to set the size of a list?

Java list sizes are dynamic. It will automatically increase every time you add an element to it and this exceeds the initial capacity. You can define the initial capacity when creating the list so that memory is allocated after the initial capacity is exhausted.

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

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

List provides size() method to get the count of elements present in the list.

Syntax

int size()
Copy after login

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

Example

The following is an example showing the usage of the 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());
   }
}
Copy after login

Output

This will produce the following results-

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
Copy after login

The above is the detailed content of In Java, how to set the size of a list?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template