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

Java Vector trimToSize() Method

Java Vector trimToSize() Method

Java Vector Java Vector


trimToSize() is a method in Java's Vector A practical method provided by the class, used to optimize Vector 's memory usage. This method adjusts the Vector 's capacity to the number of elements actually stored (size), thereby reducing unnecessary memory usage.

Method Syntax


public void trimToSize()

Class

java.util.Vector


Method Effect

Vector The class internally uses an array to store elements. When adding to the Vector , if the current array is full, theVector automatically expands (usually to 1.5 or 2 times the current capacity). Although this mechanism improves the efficiency of adding elements, it may also cause memory waste.

trimToSize() The method's job is to adjust the Vector 's internal array size to exactly hold all current elements, releasing excess memory space.

Use Cases


Method implementation principle

Source Code Analysis

The following are Vector In the class trimToSize() The method's implementation:

Example

public

synchronized

void

trimToSize

(

)

{

    modCount

++;

   

int

oldCapacity

=

elementData.

length

;

   

if

(

elementCount

<
oldCapacity
)
{
elementData
=
Arrays

.

copyOf

(

elementData, elementCount

)

;

   

}

}

Implementation Steps

  1. Increments the modification counter modCount(used for the fail-fast mechanism)
  2. Gets the capacity of the current internal array oldCapacity
  3. If the current number of elements elementCount is less than the array capacity:
  4. Use Arrays.copyOf() Creates a new array with a size of elementCount
  5. Copies the original array contents into the new array
  6. data to the child component via elementData Points the reference to the new array
  7. - Use `Arrays.copyOf()` to create a new array with a size of `elementCount` - Copy the original array contents into the new array - Point the `elementData` reference to the new array

    Notes


    Usage examples

    Basic Usage

    Example

    import

    java.util.Vector

    ;

    public

    class

    VectorTrimToSizeExample

    {

       

    public

    static

    void

    main

    (

    String

    [

    ]

    args

    )

    {

           

    // Create a Vector with an initial capacity of 10

            Vector

    <
    String
    vector
    =
    new
    Vector
    <>
    (
    10
    )

    ;

           

           

    // Add 5 elements

           

    for

    (

    int

    i

    =

    0

    ;

    i

    <

    5

    ;

    i

    ++

    )

    {

                vector.

    add

    (

    "Item "

    (

    i

    1

    )

    )

    ;

           

    }

           

           

    System

    .

    out

    .

    println

    (

    "Size: "

    vector.

    size

    (

    )

    )

    ;

         

    // Output: 5

           

    System

    .

    out

    .

    println

    (

    "Capacity: "

    vector.

    capacity

    (

    )

    )

    ;

    // Output: 10

           

           

    // Call trimToSize()

            vector.

    trimToSize

    (

    )

    ;

           

           

    System

    .

    out

    .

    println

    (

    "Capacity after trim: "

    vector.

    capacity

    (

    )

    )

    ;

    // Output: 5

       

    }

    }

    Practical Application Scenarios

    Example

    import

    java.util.Vector

    ;

    public

    class

    VectorMemoryOptimization

    {

       

    public

    static

    void

    main

    (

    String

    [

    ]

    args

    )

    {

           

    // Simulate a scenario that processes a large amount of data

            Vector

    <
    Integer
    data
    =
    new
    Vector
    <>
    (
    10000
    )

    ;

           

           

    // Add a large amount of data

           

    for

    (

    int

    i

    =

    0

    ;

    i

    <

    8000

    ;

    i

    ++

    )

    {

                data.

    add

    (

    i

    )

    ;

           

    }

           

           

    // Delete half after processing the data

           

    for

    (

    int

    i

    =

    0

    ;

    i

    <

    4000

    ;

    i

    ++

    )

    {

                data.

    remove

    (

    0

    )

    ;

           

    }

           

           

    System

    .

    out

    .

    println

    (

    "Before trim - Size: "

    data.

    size

    (

    )

                             

    ", Capacity: "

    data.

    capacity

    (

    )

    )

    ;

           

    // Output: Before trim - Size: 4000, Capacity: 10000

           

           

    // Optimize memory usage

            data.

    trimToSize

    (

    )

    ;

           

           

    System

    .

    out

    .

    println

    (

    "After trim - Size: "

    data.

    size

    (

    )

                             

    ", Capacity: "

    data.

    capacity

    (

    )

    )

    ;

           

    // Output: After trim - Size: 4000, Capacity: 4000

       

    }

    }


    Performance considerations

    Time Complexity

    trimToSize() The method's time complexity is O(n), where n is the Vector number of elements in the. This is because it needs to copy the original array into a new array.

    Space complexity

    This method creates a new array, so it temporarily uses extra memory space, but eventually releases the excess memory.

    Usage recommendation


    Comparison with Other Methods

    Comparison with ArrayList's trimToSize()

    ArrayList also has trimToSize() method; the implementation principle is similar, but ArrayList 's method is not synchronized.

    Comparison with ensureCapacity()

    Method Purpose Parameters Thread Safety
    trimToSize() Shrinks the capacity to the current size None Is
    ensureCapacity(int minCapacity) Ensures a minimum capacity Minimum capacity value Is

    Summary

    Vector.trimToSize() is a practical memory optimization method, especially suitable for the following scenarios:

    1. Vector After experiencing a large number of additions and deletions
    2. Environments with limited memory resources
    3. Vector When the contents are certain to no longer change

    Note the following when using it:

    Proper use of trimToSize() can help optimize the memory usage efficiency of Java programs.

    Java Vector Java Vector