简体   繁体   English

java Arraylist 移除元素

[英]java Arraylist remove elements

Suppose there are 10 elements in ArrayList and if i have deleted 2 elements from the middle, so the arraylist will contain 8 elements, but will the capacity be 10 or reduced to 8 at that time.假设 ArrayList 中有 10 个元素,如果我从中间删除了 2 个元素,那么 arraylist 将包含 8 个元素,但当时容量会是 10 个或减少到 8 个。

The API states: API 指出:

Each ArrayList instance has a capacity.每个 ArrayList 实例都有一个容量。 The capacity is the size of the array used to store the elements in the list.容量是用于存储列表中元素的数组的大小。 It is always at least as large as the list size.它总是至少与列表大小一样大。 As elements are added to an ArrayList, its capacity grows automatically.随着元素添加到 ArrayList,其容量会自动增长。 The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost .除了添加元素具有恒定的摊销时间成本这一事实之外,没有指定增长策略的细节

and you can always test this empirically in your debugger.并且您始终可以在调试器中凭经验对此进行测试。 After removing two elements, look at the array that backs the ArrayList , and see what it's size is.删除两个元素后,查看支持ArrayList的数组,看看它的大小。 Most likely, it's 10.最有可能的是10。

The behaviour depends on the implementation of the ArrayList.该行为取决于 ArrayList 的实现。 You can't rely on this kind of implementation details.你不能依赖这种实现细节。 The only thing you must consider is that the capacity is always greater or equal to the number of elements in your list.您必须考虑的唯一一件事是容量始终大于或等于列表中的元素数。 If you need the capacity to be exactly the number of elements (because you may want to reduce memory usage), you will have to ask it explicitly with the function trimToSize() .如果您需要容量正好是元素的数量(因为您可能想减少 memory 的使用),您必须使用 function trimToSize()明确询问它。

I think it may change because suppose we create new array list by default JVM allocate say 10 continuous locations in memory.if you put 8 or 2 or zero it will be same.我认为它可能会改变,因为假设我们默认创建新的数组列表 JVM 在 memory 中分配 10 个连续的位置。如果你放 8 或 2 或零,它将是相同的。

But is you put 15 element then it will increase it to say 20 memory locations.But if you below 10 again it should release that memory and reduce to 10 default size.但是如果你放了 15 个元素,那么它会增加 20 个 memory 位置。但是如果你再次低于 10,它应该释放 memory 并减少到 10 个默认大小。

This is dynamic allocation.For 1000 element list if you are removing the element and reduce to 2 then it is logical that it must release that memory.It should depend on number of elements removed.这是动态分配。对于 1000 个元素列表,如果您要删除元素并减少到 2,那么它必须释放 memory 是合乎逻辑的。它应该取决于删除的元素数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM