ArrayList 的最大容量是多少? [英] What is the max capacity of an ArrayList?

查看:160
本文介绍了ArrayList 的最大容量是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个 ArrayList 的初始容量是 10.当超过这个限制时,一个新的 ArrayList 被创建,容量为 (oldcapacity * 3/2) + 1,元素复制过来.

I know that the initial capacity of an ArrayList is 10. When this limit is exceeded, a new ArrayList is created with the capacity of (oldcapacity * 3 / 2) + 1, and the elements are copied over.

但是 ArrayList 的最大容量是多少?

But what is the maximum capacity of an ArrayList?

我在一次采访中被问到这个问题.面试官对默认的初始容量不感兴趣,但想知道一个ArrayList的最大容量.

I was asked this question in an interview. The interviewer was not interested in the default initial capacity, but wanted to know the maximum capacity of an ArrayList.

推荐答案

看源码:

public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

您将在此处看到相关部分:

and you will see the relevant part here:

this.elementData = new Object[initialCapacity];

所以数组列表最多可以容纳一个数组可以容纳的元素.

so the array list can at most so many elements as an array can hold.

可能会出现下一个问题:但是,一个数组可以容纳多少个元素?

the next question may arise: but then, how many elements can hold an array?

答案是:这取决于您编写代码的 VM:

the answer is: it depends on what VM are you writing the code:

在 JDK8 中:

/**
 * The maximum size of array to allocate.
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

哪里

 /**
 * A constant holding the maximum value an {@code int} can
 * have, 2<sup>31</sup>-1.
 */
@Native public static final int   MAX_VALUE = 0x7fffffff;

这篇关于ArrayList 的最大容量是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆