Home » Java programming language

Java Vector ensureCapacity() Method with Example

Vector Class ensureCapacity() method: Here, we are going to learn about the ensureCapacity() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 17, 2020

Vector Class ensureCapacity() method

  • ensureCapacity() method is available in java.util package.
  • ensureCapacity() method is used to ensure the capacity of this Vector when required or in other words, we can say this method is used to extend the capacity of this Vector when required.
    The formula of New Capacity:
    New Capacity = old capacity + minimum capacity (min_cap)
  • ensureCapacity() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • ensureCapacity() method does not throw an exception at the time of ensuring capacity.

Syntax:

    public void ensureCapacity(int min_cap);

Parameter(s):

  • int min_cap – represents the required minimum capacity (min_cap).

Return value:

The return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void ensureCapacity(int min_cap) method 
// of Vector 

import java.util.*;

public class EnsureCapacityOfVector {
    public static void main(String[] args) {
        // Instantiates a Vector object  with
        // initial capacity of "10"
        Vector < String > v = new Vector < String > (10);

        // By using add() method is to add the
        // elements in this v
        v.add("C");
        v.add("C++");
        v.add("JAVA");

        // Display Vector Capacity
        System.out.println("v.capacity(): " + v.capacity());

        // By using ensureCapacity() method is to
        // extend the capacity
        v.ensureCapacity(20);

        // Display Updated Capacity
        System.out.println("v.ensureCapacity(20): " + v.capacity());
    }
}

Output

v.capacity(): 10
v.ensureCapacity(20): 20






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.