ArrayList的容量

发布于 2024-09-16 02:02:56 字数 355 浏览 4 评论 0原文

可能的重复:
Java中如何获取ArrayList的容量?< /a>

如何查找ArrayList的容量?

Possible Duplicate:
How to get the capacity of the ArrayList in Java?

How to find the capacity of an ArrayList?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

醉生梦死 2024-09-23 02:02:56

我很好奇,你需要它做什么?您应该知道,容量并不是(听起来)可以放入 ArrayList 的上限。它是一个值,表示您可以将多少数据放入列表中,而无需强制它重新分配内部数组。基本上,容量的概念只是为了让您稍微调整性能。

不管怎样,也许你已经知道了,所以真正的答案来了。

API 为 ArrayList 提供的接口根本不支持此类用例。造成这种情况的原因有很多。原因之一是你不应该关心这个。 ArrayList 被认为是一个无界数组,它抽象了诸如容量之类的细节。

最接近控制容量的方法是通过构造函数 ArrayList(int initialCapacity),以及两个方法trimToSize()ensureCapacity(int minCapacity)

然而,为了好玩,我设法通过丑陋的反射黑客解决了这个问题(不要使用这个):

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;
    }
}

输出:

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

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.

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.

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).

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
昨迟人 2024-09-23 02:02:56

不,你不能! Java ArrayList 不提供访问其当前容量的方法。

您只能使用构造函数 ArrayList(int initialCapacity) 或通过调用 ensureCapacity()

No you cannot ! Java ArrayList do not provide a way to access its current capacity.

You can only construct an ArrayList specifying an initial capacity using constructor ArrayList(int initialCapacity) or increase the capacity by calling ensureCapacity().

黑寡妇 2024-09-23 02:02:56

ArrayList 是一个可自动增长的List 元素的抽象。您很少需要了解其容量。考虑《Effective Java 第 2 版》第 52 条:通过接口引用对象。实际上,您甚至不应该关心它是 ArrayList 还是 LinkedList;它只是一个列表

也就是说,您可能会对这些方法感兴趣:

The ArrayList is an abstraction for 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.

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.
  • 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 an ArrayList instance.
小矜持 2024-09-23 02:02:56

根据规范:“容量是用于存储列表中元素的数组的大小。它始终至少与列表大小一样大。随着元素添加到 ArrayList,其容量会自动增长。详细信息除了添加元素具有恒定的摊销时间成本这一事实之外,没有指定增长策略。”

因此,无法得知当前容量是多少,也无法得知其增长情况。

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."

So there's no way to tell what the current capacity is, nor how it grows.

那片花海 2024-09-23 02:02:56

API 不提供它。
在内部,每当在满容量时调用 add(..) 时,容量就会乘以一个因子。然而,Java 规范没有提及这个常数因子……Sun 的实现使用因子 1.5,因此容量的上限为 1.5*size()。

请记住,您可以使用trimToSize()来“压缩”列表并使容量等于size()。

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.

Remember that you can use trimToSize() to "compact" the list and make the capacity equal to size().

蒗幽 2024-09-23 02:02:56

我要逆势而行……用户有一个问题,尽管没有上下文。如果没有上下文,就没有必要知道容量,因为后备数组会增长以容纳...

您可以执行以下操作来确定 ArrayList 的容量。副作用是后备数组将被修剪为数组中元素的确切数量:

ArrayList list = new ArrayList();
//add a bunch of elements
list.trimToSize();
System.out.println("Capacity = " + list.size());

享受吧!

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 list = new ArrayList();
//add a bunch of elements
list.trimToSize();
System.out.println("Capacity = " + list.size());

Enjoy!

情话难免假 2024-09-23 02:02:56

您无需担心容量,这是内部实现细节。如果内部数组填满,那么它将扩展。您可以使用 size() 方法了解 ArrayList 中当前有多少元素。

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.

ㄟ。诗瑗 2024-09-23 02:02:56

您在运行时需要它还是在执行测试时可以获取它?如果进行测试,您通常可以使用您最喜欢的 IDE 调试器查看容量。我没有确切的数字,但 1.7 通常是容量增长的大小。因此,如果您创建一个包含 10 个项目的数组列表,java 会将其大小设置为 17。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文