Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java ArrayList ensureCapacity() Method

Java ArrayList ensureCapacity() Method

Java ArrayList Java ArrayList

The ensureCapacity() method is used to set the capacity of the dynamic array to the specified size.

The syntax of the ensureCapacity() method is:


arraylist.ensureCapacity(int minCapacity)

**Note:** arraylist is an object of the ArrayList class.

Parameter Description:

Return Value

No value is returned.

Example

ArrayList sureCapacity() usage example:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a dynamic array

        ArrayList

<
String
sites
=
new
ArrayList
<>
(
)

;

       

       

// Set the capacity of the arraylist

        sites.

ensureCapacity

(

3

)

;

       

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

       

System

.

out

.

println

(

"Website list: "

sites

)

;

   

}

}

The output of the above program is:


网站列表: [Google, Runoob, Taobao]

In the example above, we created an array named sites.

Note this line:


sites.ensureCapacity(3);

We used the ensureCapacity() method to resize the dynamic array to hold 3 elements.

ArrayList in Java can be dynamically resized. That is, if we add more than 3 elements to the arraylist, it will automatically adjust its size, for example:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a dynamic array

        ArrayList

<
String
sites
=
new
ArrayList
<>
(
)

;

       

       

// Set the capacity of the arraylist

        sites.

ensureCapacity

(

3

)

;

       

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

       

       

// Add a fourth element

        sites.

add

(

"Wiki"

)

;

       

System

.

out

.

println

(

"Website list: "

sites

)

;

   

}

}

The output of the above program is:


网站列表: [Google, Runoob, Taobao, Wiki]

In the example above, we used the ensureCapacity() method to resize the dynamic array to hold 3 elements. However, when we add a 4th element to the arraylist, the arraylist automatically resizes.

Then, if the arraylist can automatically resize itself, why use the ensureCapacity() method to adjust the size of the arraylist?

This is because if we use the ensureCapacity() method to adjust the size of the arraylist, the arraylist will immediately adjust to the specified capacity. Otherwise, the arraylist is resized every time an element is added.

Java ArrayList Java ArrayList