- 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
Advertisements