如何在Java中获取ArrayList的容量? [英] How to get the capacity of the ArrayList in Java?

查看:23
本文介绍了如何在Java中获取ArrayList的容量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,Java ArrayList 是使用数组实现的,初始化容量为 10,大小增加 50% .如何获取当前 ArrayList 容量而不是 ArrayList 的大小.

Its known that Java ArrayList is implemented using arrays and initializes with capacity of 10 and increases its size by 50% . How to get the current ArrayList capacity not the Size of the ArrayList.

谢谢

推荐答案

我认为这是不可能的.你的用例是什么?我相信 C# ArrayLists 有一个 .capacity 属性,但 Java ArrayList 类不公开此信息.

I don't think this is possible. What is your use case? I believe C# ArrayLists have a .capacity property, but the Java ArrayList class doesn't expose this information.

你有一个接受初始容量参数的构造函数,你有 ensureCapacity() 方法,你可以用它来减少增量重新分配的数量.

You have the constructor that takes an initial capacity argument, and you have the ensureCapacity() method which you could use to reduce the amount of incremental reallocation.

如果您真的担心内存使用,您还可以使用 trimToSize() 方法.

You also have the trimToSize() method you can use if you are really worried about memory usage.

这篇关于如何在Java中获取ArrayList的容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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