简体   繁体   English

将为Java LinkedList分配多少空间?

[英]How much space will be allocated for Java LinkedList?

I am reading the source code of Java LinkedList, and note that the constructor of LinkedList is like this: 我正在阅读Java LinkedList的源代码,并注意LinkedList的构造函数是这样的:

public LinkedList() {
    header.next = header.previous = header;
}

How much space will be allocated to this initialization, the header seems to create infinite recursion by pointing to itself. 标头将分配多少空间用于此初始化,它似乎通过指向自身来创建无限递归。

It allocates a single node in the initialization of the header instance variable: 它在header实例变量的初始化中分配一个节点:

private transient Entry<E> header = new Entry<E>(null, null, null);

The code in the constructor to which you refer allocates no memory; 您所引用的构造函数中的代码不分配内存。 it merely sets up the pointers to an initial state. 它只是将指针设置为初始状态。 There is no "infinite recursion", because internal traversal caters for this situation. 没有“无限递归”,因为内部遍历可满足这种情况。

I'm not 100% sure what you mean by "how many space", but if you mean how much space will be allocated in memory - it's just one field initially. 我不是100%知道“多少空间”是什么意思,但是如果您是指要在内存中分配多少空间-最初只是一个字段。 Even though the header pointer points to itself, all pointers still only point to a single address space in memory. 即使头指针指向自身,所有指针仍仅指向内存中的单个地址空间。 Mind you, I'm not even sure it will initially point anywhere, I think they will only be assigned null values at first. 请注意,我什至不确定它最初是否会指向任何地方,我认为一开始它们只会被分配空值。

A simple example. 一个简单的例子。

String a = "Hello"
String b = a;
String c = b;

The String "Hello" will only occur once in the memory, even though it has several pointers to it. 字符串“ Hello”将在内存中仅出现一次,即使它具有多个指向它的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM