Java ArrayList的容量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3564837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capacity of ArrayList
提问by user430532
Possible Duplicate:
How to get the capacity of the ArrayList in Java?
How to find the capacity of an ArrayList
?
如何找到一个的容量ArrayList
?
回答by Gopi
No you cannot ! Java ArrayList do not provide a way to access its current capacity.
你不能 !Java ArrayList 不提供访问其当前容量的方法。
You can only construct an ArrayList specifying an initial capacity using constructor ArrayList(int initialCapacity)or increase the capacity by calling ensureCapacity().
您只能使用构造函数ArrayList(int initialCapacity)构造一个指定初始容量的ArrayList或通过调用ensureCapacity()增加容量。
回答by Noel M
You don't need to worry about the capacity, that is an internal implementation detail. If the internal array fills, then it will expand. You can find out how many elements are currently in your ArrayList with the size()
method.
您无需担心容量,这是一个内部实现细节。如果内部数组填满,那么它将扩展。您可以使用该size()
方法找出 ArrayList 中当前有多少个元素。
回答by Jeroen Rosenberg
From the specification: "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. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost."
来自规范:“容量是用于存储列表中元素的数组的大小。它始终至少与列表大小一样大。随着元素添加到 ArrayList,其容量会自动增长。详细信息除了添加元素具有恒定的摊销时间成本之外,没有指定增长政策。”
So there's no way to tell what the current capacity is, nor how it grows.
因此,无法确定当前的容量是多少,也无法确定它是如何增长的。
回答by Steve
Do you need this at runtime or is it ok to get while performing testing? If its testing you can usually see the capacity using your favourite IDE debugger. I don't have the exact number, but 1.7 is usually the capacity growth size. So if you create an arraylist with 10 items, java will make it size 17.
你在运行时需要这个还是在执行测试时可以得到它?如果进行测试,您通常可以使用您最喜欢的 IDE 调试器查看容量。我没有确切的数字,但 1.7 通常是容量增长的大小。因此,如果您创建一个包含 10 个项目的数组列表,java 将使其大小为 17。
回答by Eyal Schneider
The API doesn't provide it. Internally, the capacity is multiplied by a factor whenever add(..) is called while in full capacity. However, the Java specification doesn't say anything about this constant factor... Sun's implementation uses a factor of 1.5, so you have an upper bound of 1.5*size() for the capacity.
API 不提供它。在内部,每当在满负荷状态下调用 add(..) 时,容量都会乘以一个因子。但是,Java 规范并没有说明这个常数因子……Sun 的实现使用了 1.5 的因子,因此容量的上限为 1.5*size()。
Remember that you can use trimToSize() to "compact" the list and make the capacity equal to size().
请记住,您可以使用 trimToSize() 来“压缩”列表并使容量等于 size()。
回答by polygenelubricants
The ArrayList
is an abstractionfor an automatically growable List
of elements. You rarely need to know its capacity. Consider Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces. As much as practical, you should not even care if it's an ArrayList
or a LinkedList
; it's just a List
.
的ArrayList
是一个抽象为一个可增长的自动List
元素。您很少需要知道它的容量。考虑Effective Java 2nd Edition,Item 52:通过其接口引用对象。尽可能实用,您甚至不应该关心它是 anArrayList
还是 a LinkedList
;它只是一个List
.
That said, these methods may be of interest to you:
也就是说,您可能会对这些方法感兴趣:
ArrayList(int initialCapacity)
- Constructs an empty list with the specified initial capacity.
void ensureCapacity(int minCapacity)
- Increases the capacity of this
ArrayList
instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
- Increases the capacity of this
void trimToSize()
- 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 anArrayList
instance.
- Trims the capacity of this
ArrayList(int initialCapacity)
- 构造一个具有指定初始容量的空列表。
void ensureCapacity(int minCapacity)
ArrayList
如有必要,增加此实例的容量,以确保它至少可以容纳由最小容量参数指定的元素数量。
void trimToSize()
- 将此
ArrayList
实例的容量修剪为列表的当前大小。应用程序可以使用此操作来最小化ArrayList
实例的存储。
- 将此
回答by aioobe
I'm curious, what do you need it for? You should know that the capacity is not (as it may sound) an upper limit of how much you can put into the ArrayList. It's a value representing how much data you can put into the list, without forcing it to reallocate it internal array. Basically, the notion of capacity is only there in order for you to tweak the performance slightly.
我很好奇,你需要它做什么?您应该知道容量不是(听起来可能)您可以放入 ArrayList 的上限。它是一个值,表示您可以将多少数据放入列表,而不强制它重新分配内部数组。基本上,容量的概念只是为了让您稍微调整性能。
Anyway, perhaps you already know that, so here comes the actual answer.
不管怎样,也许你已经知道了,所以这里是实际的答案。
The interface provided by API for ArrayList simply doesn't support such use case. There are many reasons for this. One reason is that you shouldn't care about this. The ArrayList is to be thought of as an unbounded array which abstracts away from details such as capacity.
API 为 ArrayList 提供的接口根本不支持这种用例。这件事情是由很多原因导致的。一个原因是你不应该关心这个。ArrayList 被认为是一个无界数组,它从容量等细节中抽象出来。
The closest you can get to controlling the capacity is through the constructor ArrayList(int initialCapacity)
, and the two methods trimToSize()
and ensureCapacity(int minCapacity)
.
最接近控制容量的是通过构造函数ArrayList(int initialCapacity)
,以及两个方法trimToSize()
和ensureCapacity(int minCapacity)
。
For fun however, I managed to solve it through an ugly reflection-hack(don't use this):
然而,为了好玩,我设法通过一个丑陋的反射黑客来解决它(不要使用这个):
import java.lang.reflect.Field;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>(3);
for (int i = 0; i < 17; i++) {
list.add(i);
System.out.format("Size: %2d, Capacity: %2d%n",
list.size(), getCapacity(list));
}
}
static int getCapacity(ArrayList<?> l) throws Exception {
Field dataField = ArrayList.class.getDeclaredField("elementData");
dataField.setAccessible(true);
return ((Object[]) dataField.get(l)).length;
}
}
Output:
输出:
Size: 1, Capacity: 3
Size: 2, Capacity: 3
Size: 3, Capacity: 3
Size: 4, Capacity: 5
Size: 5, Capacity: 5
Size: 6, Capacity: 8
Size: 7, Capacity: 8
Size: 8, Capacity: 8
Size: 9, Capacity: 13
Size: 10, Capacity: 13
Size: 11, Capacity: 13
Size: 12, Capacity: 13
Size: 13, Capacity: 13
Size: 14, Capacity: 20
Size: 15, Capacity: 20
Size: 16, Capacity: 20
Size: 17, Capacity: 20
回答by Tim Reddy
I'm going to buck the trend here...the user has a question albeit with no context. Without context, knowing the capacity is unnecessary as the backing array will grow to accommodate...
我将在这里逆势而行……用户有一个问题,尽管没有上下文。没有上下文,知道容量是不必要的,因为后备阵列将增长以容纳......
You can do the following to know for certain what the capacity is with your ArrayList. The side effect is the backing array will be trimmed to the exact number of elements in the array:
您可以执行以下操作来确定您的 ArrayList 的容量是多少。副作用是后备数组将被修剪为数组中元素的确切数量:
ArrayList list = new ArrayList();
//add a bunch of elements
list.trimToSize();
System.out.println("Capacity = " + list.size());
Enjoy!
享受!