Home >Java >javaTutorial >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);
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.
int size()
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, Integer.MAX_VALUE is returned.
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()); } }
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
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!