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);
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.
There would be no point in allocating memory to the list beforehand, since LinkedList does not have capacity.
Its model is not based on an array but rather a true linked list, and so there is no need and further it would not make sense. It doesn't make much sense to have empty links like you have empty array items.
Why would you need a capacity on a LinkedList? A LinkedList does not work with fixed sized arrays. Every LinkedListElement has a pointer (a link!) to the next Element in the list. Which Because of that it is possible to add an element to a linked list in constant time. But it is costly to have random access to the elements in the List. You need to go through all the Elements in the list until you reach your destination.
Why would LinkedList have an initial capacity?
ArrayList is backed up by an array, so the initial capacity is the initial size of the array. LinkedList has no need of that.
Linkedlist does not need an initial value. Thats is the primary difference between array and linked list.
array will end somewhere. But linkedlist not. Linked list does not work on boundary values.
When you declare an array you have to know its size because pointers need to be created in memory. A linked list does not need this because there is no need for pointers to memory before any object is added to the list.
A linked list is defined recursively as:
an empty list
en element that points to the empty list
therefore whenever you add an element, you allocate memory (or rather in Java the compiler does this) when you create the element, and then when you add it to the list it now points to the list (or the last element in the list points to it).
So you don't need to declare initial size of linked list because a linked list always starts with the empty list, and when an element is added it points to the list.
ArrayList And LinkedList both have implementation class of List Interface.
ArrayList is using Resizable Array or Grow-able Array.In array Data structure using Contiguous memory allocation and with the help of that we can access array's element with index. When we declare any array then we should declare initial capacity because finding of Contiguous memory blocks for storing array's element.
LinkedList is using double linked list as under Line data structure. In linked list data structure using non contiguous memory allocation and using head and tail concept for access these element. So in LinkedList we don't need to any initial capacity.
Related
What is index in linked List of java because linked list is not a continuous memory ???
List l=new linkedList();
l.get(index);
l.add(index);
what is index in linkedList of java because linked list is not allocate continuous memory
If you are referring to java.util.LinkedList, the index is simply the position of an element in the List. Any List implementation is an ordered Collection, so elements can be accessed via their index.
However, for LinkedList, methods such as get(index) are not efficient, since they have to traverse the List from its beginning or from its end (depending on which is closer to the required index), which takes linear time.
I am having an issue in understanding this.
while we do
List<Integer> list = Arrays.asList(array);
we can not use methods like add, remove on that list. I know that Arrays.asList() returns a fixed-sized list.
What I don't understand is if we create a list with initial capacity specified like
List<Integer> list2 = new ArrayList<Integer>(10);
we can perform all the operations on that list. What is the difference between fixed-sized list and list with initial capacity specified?
I have read many answers on this but having such a hard time understanding this. Can anyone explain?
Thanks.
Arrays.asList(array) returns an object of type java.util.Arrays.ArrayList, which does not support add and remove operations.
While the code below will return an object of type java.util.ArrayList, which supports add and remove operations.
List<Integer> list2 = new ArrayList<Integer>(10);`
Very simply, Arrays.asList is so you can use List methods with an array. ArrayList(int) is for when you need to create a really large ArrayList and want to help speed things up a bit.
In more detail: the List returned by asList is intended as a wrapper to an array. Since you cannot resize an array, the methods that change the size of a List are unimplemented. Most of the time I just use asList to add a fixed number of elements to a collection simply. eg.
new ArrayList<String>(Arrays.asList("hello", "world"));
Confusingly, the implementation of ArrayList is very similar -- it's a List backed by an array. However, ArrayList allows you to change it's size. To do this it keeps a separate fields about the how many objects are in the list and the length of the backing array. Add an element and the ArrayList just sets array[size] to the element and then increments the size field. But what if array[size] is out of bounds? At this point the ArrayList creates a new, larger array and copies over the elements from the previous backing array. However, if you are creating a large List then this constant creation of new backing arrays can start to take up a lot of time. As such, if you know the approximate number of elements that will be in the List you can use this to inform the ArrayList about the size of the initial backing array it should create. This is what the ArrayList(int) constructor is for. Only in exceptional circumstances will you need to worry about giving the ArrayList a length hint.
When I declare LinkedList like:
List<String> names = new LinkedList<String>();
it does not support any of the LinkedList's special methods (ex: names.peekLast(), names.pollFirst() )
But when I declare like:
LinkedList<String> names = new LinkedList<String>();
then it supports these methods.
Yes, it is obvious that reason is the reference, as LinkedList contains that's methods and List does not have!
But my question is that when I want to work with LinkedList, which one is better and correct? Or what is the usage of them?
If you need to use LinkedList methods that don't exist in List, you should use a LinkedList reference (you could use a List reference and cast to LinkedList in order to call LinkedList specific methods, but that would make less sense).
Otherwise, it is preferable to use the List interface for holding the reference, since it makes your code more generic, since it won't depend on any specific List implementation.
Well, List is basically backed by an array which is usually bigger than the current number of items. The elements are put in an array, and a new array is created when the old one runs out of space. This is fast for access by index, but slow at removing or inserting elements within the list or at the start. Adding/removing entries at the end of the list is reasonably cheap.
LinkedList is a doubly-linked list - each node knows its previous entry and its next one. This is fast for inserting after/before a particular node (or the head/tail), but slow at access by index.
LinkedList will usually take more memory than List because it needs space for all those next/previous references - and the data will probably have less locality of reference, as each node is a separate object. On the other hand, a List can have a backing array which is much larger than its current needs.
Reference from Difference between List<T> and LinkedList<T>
You can also refer to oracle docs
Linked List
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
List
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
Well there is very simple explanation regarding that is List<> is like array which is making new array when its running out of space. And LinkedList<> is like doubly-linked list where each an every node will have link of previous node as well as next node.
More of that you can search from oracle docs
https://docs.oracle.com/javase/7/docs/api/java/util/List.html
and
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
You can differentiate by your self. :)
This was on my Java question paper which one out of the two is best to use for a set of indexed objects? ArrayList or LinkedList I thought it is LinkedList. What is the correct answer and please explain why?
Linked lists are not random access; to retrieve an element at some index, you have to traverse the list from the beginning until you reach that index. Arrays (on which ArrayList is built), on the other hand, are random access, which means you can simply retrieve an element at a given index in constant time. Therefore ArrayList would be more appropriate to store indexed objects.
ArrayLists are specifically for indexed data. LinkedLists aren't an indexed data structure. With an ArrayList, you provide the index, the ArrayList provides the stored value. With a LinkedList, you have to traverse the list to get the stored value.
is it somehow possible to get a sorted List view of a List with the elements from the original List, modify the elements, for example set a property, but the original List should reflect the changes?
Background is I'm sorting two Lists, then for each equal element I'm setting a property (basically it's the intersection) but finally I need the unsorted List with the modified elements.
kind regards,
Johannes
Probably the simplest thing to do is add the elements to a new list, sort that list, and when you modify the elements, the original elements will still be modified...
List<?> origA;
List<?> origB;
List<?> newA = new ArrayList<?>(origA);
List<?> newB = new ArrayList<?>(origB);
Collections.sort(newA);
Collections.sort(newB);
// do mods
If the List holds references to objects (not primitive data types), then just copy the list, sort it and modify the elements.
Does it have to be a list? If you keep your elements in a TreeSet, they will always be sorted as you iterate through them, even after you add/remove the elements. Remember though that modifying an element already in the TreeSet may break the sort order. You can remove and add the element to the TreeSet to get around that.
If you have to use a list, you can use Collections.sort(List list) after adding or modifying an element. Of course, if you have to call it often, there will be a performance hit. If performance is a concern, you can just insert the new element (or move the modified one) to maintain the sorted order, which will be cheaper than sorting it: O(n) vs O(n*log(n))