如何将 arrayList 大小设置为 null?
String a []= {null,null,null,null,null};
//add array to arraylist
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a));
System.out.println(choice.size());
当所有元素都设置为 null
时,为什么 arrayList choice
的大小为 5
String a []= {null,null,null,null,null};
//add array to arraylist
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a));
System.out.println(choice.size());
Why the size of the arrayList choice
is 5 when all the elements have been set to null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为ArrayList仍然包含5个Object。它们是 null,但它们是对象,因此存在于列表中!
您可以通过调用choice.clear();来清空ArrayList
Because the ArrayList still contains 5 Objects. They are null, but they are objects, thus present in the list!
You can empty the ArrayList, by calling
choice.clear();
我认为让您感到困惑的是您将 ArrayList 视为对象的 ArrayList,而不是对象引用的 ArrayList。
对象的 ArrayList 表示对象的引用的索引可访问列表。
对于这样的引用来说,不引用真实对象而是“null”是有效的。
因此,您有五个参考“槽”,每个槽的值为 null。
这与一系列四个空值或零个空值不同。
看看你的初始和原始字符串数组 - 它的长度是五,而不是零。
或者更简单的是,当你有一个带有 Object 类型字段的类时,它仍然占用空间,无论它实际上是引用某些东西还是为空。否则,您将无法实例化该类,并且在实际向该字段分配某些内容时不需要重新分配它。
I think that what is confusing you is that you are thinking of the ArrayList as an ArrayList of objects, not as an ArrayList of references to objects.
An ArrayList of Object represents an index-accessible list of references to objects.
It is valid for such a reference to not refer to a real object but instead be "null".
Hence, you have five reference "slots", each with a value of null.
This is not the same as a series of four nulls, or zero nulls.
Look at your initial and primitive array of strings - its length is five, not zero.
Or even simpler, when you have a class with a field of type Object, it still takes space, regardless of whether it is actually referring to something or is null. Otherwise, you wouldn't be able to instantiate the class and not need to reallocate it when you actually assigned something to the field.
来自 ArrayList 的 Javadocs:
ArrayList 可以容纳 null 元素,因此大小为 5。请记住,如果您只是声明一个
new ArrayList(5)
,它的初始容量将为 5,但size()
将为 0。From the Javadocs for ArrayList:
ArrayLists can hold null elements, so the size is five. Keep in mind that if you simply declare a
new ArrayList(5)
, it will have a initial capacity of 5, but thesize()
will be 0.这是因为 ArrayList 不为 null,它保存了 5 个对象(全部为 null),无论如何 ArrayList 永远不会有 null 大小,至少大小为 0(零),并且如果 ArrayList 未初始化(为 null)当你尝试访问函数 size() 时,它会抛出 NullPointerException。我希望这些信息对你有用,抱歉我的英语不好:(
This is because the ArrayList is not null, it holds five objects (all are null), anyway an ArrayList never will have a null size, at least the size is 0 (zero), and if the ArrayList is not initialized (is null) and you try to access to the function size() it will threw a NullPointerException. I hope this information will be useful for you, and sorry for my bad english :(