- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the best way to check capacity in Java?
To check capacity in Java, firstly create a list and add elements. After that use ensureCapacity() and increase the capacity.
Let us first create an ArrayList and add some elements −
ArrayList<Integer>arrList = new ArrayList<Integer>(5); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500);
Now, increase the capacity of the ArrayList −
arrList.ensureCapacity(15);
Meanwhile, with the size() method, you can check the current size of the ArrayList as well.
Example
import java.util.ArrayList; public class Demo { public static void main(String[] a) { ArrayList<Integer>arrList = new ArrayList<Integer>(5); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); System.out.println("Size of list = "+arrList.size()); arrList.ensureCapacity(15); for (Integer number: arrList) { System.out.println(number); } arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); System.out.println("Updated list..."); System.out.println("Size of list = "+arrList.size()); arrList.ensureCapacity(15); for (Integer number: arrList) { System.out.println(number); } } }
Output
Size of list = 7 100 200 300 400 500 600 700 Updated list... Size of list = 12 100 200 300 400 500 600 700 100 200 300 400 500
- Related Articles
- What is best way to check if a list is empty in Python?
- Best way to null check in Kotlin
- What is the correct way to check if String is empty in Java?
- What is the best way to concatenate strings in JavaScript?
- What is the best way to stop Brain Drain?
- What is the best way to earn money online?
- What is the best way to compare two strings in JavaScript?
- What is the best way to add an event in JavaScript?
- What is the best way to log a Python exception?
- What is the best way to initialize a JavaScript number?
- What is the best way to learn Python and Django?
- What is the best way to do optional function parameters in JavaScript?
- What is the best way to break from nested loops in JavaScript?
- What is the best way to handle list empty exception in Python?
- What is the best way to iterate over a Dictionary in C#?

Advertisements