问题描述
我想知道为什么 LinkedList
没有 initialCapacity
.
I wonder why LinkedList
doesn't have initialCapacity
.
我知道什么时候使用 ArrayList
以及什么时候使用 LinkedList
.
I know good when to use ArrayList
and when LinkedList
.
定义集合最终大小的好习惯,如:
Its good practice to define Collection final size like:
List<String> arraylist = new ArrayList<String>(5);
以LinkedList
为例:
List<String> linkedlist = new LinkedList<String>(); // right way
但是
List<String> arraylist = new LinkedList<String>(5); // compilation error
有人可以就这个问题发表一些看法吗?
Can somebody spread a light on that issue?
顺便说一句,我可以写
List<String> arraylist = new ArrayList<String>(5);
List<String> linkedlist = new LinkedList<String>(arraylist);
推荐答案
LinkedList 本质上没有容量",因为在项目添加到列表之前它不会为项目分配内存.LinkedList 中的每一项都持有指向列表中下一项的指针.
LinkedList by nature does not have "capacity", since it does not allocate memory to the items before the items are added to the list. Each item in a LinkedList holds a pointer to the next in the list.
事先为列表分配内存是没有意义的,因为 LinkedList 没有容量.
There would be no point in allocating memory to the list beforehand, since LinkedList does not have capacity.
这篇关于为什么LinkedList 在java 中没有initialCapacity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!