Is the trimtosize() method of the Java array list redundant?

I don't think the trimtosize () method in Java's ArrayList is necessary My understanding is:

Let's look at an integer array:

int[] a = new int[10]; //This allocates ten free slots proactively.

The main advantage of ArrayList is that it can dynamically create arrays at runtime, thus saving memory ArrayList < integer > ARL = new ArrayList < integer > (10) of the current code; Ten vacancies will not be allocated actively; Instead, add slots only when storing data

Now the Java specification says that trimtosize() will delete unused space from the ArrayList, but according to my understanding, there will be no unused space in the ArrayList, because space is created only when data is available, and when data is available, unused or available space will be zero

Solution

Your understanding is incorrect If you create a new ArrayList < integer > (10), it will create an integer array with a size of 10 and fill the ArrayList with null values as the core of its data model It will fill some or all slots according to the number of items. If the number of items exceeds its possible size, it will increase the size of the underlying array The trimtosize() method has a dependency

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>