

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- How do I find the size of a Java list?
- How do I set a minimum window size in Tkinter?
- How do I empty a list in Java?
- How do I search a list in Java?
- How do we get the size of a list in Python?
- How do I insert elements in a Java list?
- Set the size of a Vector in Java
- How do I set the timezone of MySQL?
- How do we get size of a list in Python?
- How do I change the font size of ticks of matplotlib.pyplot.colorbar.ColorbarBase?
- How do I get length of list of lists in Java?
- How do I determine the size of my array in C#
- How do I find out the size of a canvas item in Tkinter?
- How do you create a list from a set in Java?
- How do you turn a list into a Set in Java?
Advertisements