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

Java ArrayList trimToSize() Method · Private Archive

Java ArrayList trimToSize() Method · Private Archive

Java ArrayList Java ArrayList

Java ArrayList trimToSize() Method

The trimToSize() method is used to adjust the capacity in the dynamic array to the number of elements in the array.


arraylist.trimToSize();

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

Parameter Description:

Return Value

The syntax of the trimToSize() method is:

Example

No return value; it only changes the capacity of the arraylist.

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a dynamic array

        ArrayList

<
String
sites
=
new
ArrayList
<>
(
)

;

       

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        sites.

add

(

"Taobao"

)

;

       

System

.

out

.

println

(

"ArrayList : "

sites

)

;

       

The following example demonstrates the use of the trimToSize() method:

        sites.

trimToSize

(

)

;

       

System

.

out

.

println

(

// Adjust capacity to 3

sites.

size

(

)

)

;

   

}

}

The output of the above program is:


ArrayList : [Google, Runoob, Taobao]
ArrayList 大小: 3

"ArrayList size: "

In the example above, the trimToSize() method sets the capacity of the dynamic array to the number of elements in sites (i.e., 3).

Advantages of ArrayList trimToSize()

We know that the capacity of an ArrayList changes dynamically. So what is the benefit of using the ArrayList trimToSize() method?

To understand the advantage of the trimToSize() method, we need to study how ArrayList works internally.

ArrayList internally uses an array to store elements; when the array is full, a new array is created whose capacity is 1.5 times that of the current array.

At the same time, all elements are moved to the new array. Suppose the internal array is full and we now add 1 more element; the ArrayList capacity expands by the same ratio (i.e., 1.5 times the previous array).

In this case, there will be some unallocated space in the internal array.

Java ArrayList Java ArrayList