gpt4 book ai didi

java - 包含一个字符串的列表是否等于(在内存使用中)包含一个字符串和一个空对象的列表?

转载 作者:行者123 更新时间:2023-12-04 06:03:05 24 4
gpt4 key购买 nike

我想弄清楚一些事情。
这是:

    List <String> list = new ArrayList<String>();
list.add("abc");
list.add(null);
等于这个
    List <String> list = new ArrayList<String>();
list.add("abc");
在内存使用?
谢谢!

最佳答案

initial capacity ArrayList 的值为 10(引用)。也就是说,底层数组的大小为 10,即使您的集合中只有一个条目。这些引用将默认为 null,因此将第二个引用设置为 null 既不会影响 arraylist 的内部状态(就底层数组而言),也不会影响其内存消耗。

如果您添加了第十一项(设置为 null),则 ArrayList会扩大它的容量,因此你会消耗更多的内存,而是因为 ArrayList 为你的 String 创建了额外的存储桶引用。

从上面链接的文档:

Each ArrayList instance has a capacity. 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.

关于java - 包含一个字符串的列表是否等于(在内存使用中)包含一个字符串和一个空对象的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com