Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

java - ArrayList.trimToSize() method

Can I use ArrayList.trimToSize() method in dynamic arrayList ?

  1. If I use it , what will be happened ?
  2. Can I get any benefits on using this method on dynamic ArrayList.
  3. In which case, I should use this method.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the docs you link yourself:

Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

Internally an ArrayList stores an array that holds all the items. At certain moments the ArrayList will "expand" this array by copying all values into a larger array. This happens whenever an item is being added and the required capacity is bigger than the current one. What happens at this point is the following line of code:

int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);

In essence this will create a new array that is 1.5 times the size of the current one. What this method does is resize the internal array so that it has no empty space left.

  1. Nothing will happen that's visible to you. You won't lose any data, it's just smaller backing array. Adding data to the arraylist will again expand the array normally.

  2. I assume you mean a "normal" ArrayList. If you use this, you will reduce the memory used but it will also be futile if you will still add data after that AND it is pretty useless for small lists. If you have an ArrayList of many, many items and you're sure you don't want to add anymore then you can call this method to reduce some memory footprint.

  3. See above. I don't think it's very likely you'll ever use this.

trimToSize() from the source:

public void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
        elementData = Arrays.copyOf(elementData, size);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...