why LinkedList doesn't have initialCapacity in java?

Maxim Shoustin picture Maxim Shoustin · Sep 27, 2013 · Viewed 20.3k times · Source

I wonder why LinkedList doesn't have initialCapacity.

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);

For LinkedList for example:

List<String> linkedlist = new LinkedList<String>(); // right way

but

List<String> arraylist = new LinkedList<String>(5); // compilation error

Can somebody spread a light on that issue?

[EDIT]

BTW, I can write

List<String> arraylist = new ArrayList<String>(5);
List<String> linkedlist = new LinkedList<String>(arraylist);

Answer

Kimi picture Kimi · Sep 27, 2013

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.

http://www.stoimen.com/blog/wp-content/uploads/2012/06/0.-Arrays-vs.-linked-list.png

There would be no point in allocating memory to the list beforehand, since LinkedList does not have capacity.