Java Collection (LinkedList Concepts) - java

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. :)

Related

How to simulate a pointer to LinkedList element in Java?

I need an object, that
points to element of linked list
can be iterated to next
can be cloned
all operations should be O(1)
I don't see proofs, that ListIterator complies these requirements. Particularly, I don't see it is Cloneable.
There is no class that fulfill all the criteria for java.util.LinkedList. You need to implement your own linked list for that.
java.util.LinkedList and it's iterators have limitations. Assigning an iterator only creates another reference to the same iterator object, so not "cloneable" assuming that's what you mean by "cloneable". If you create multiple iterators to a list, if any nodes are added or removed from a list, all iterators (except one used for add) will be invalidated. There's no equivalent of C++ std::list::splice(), which can move one or mode nodes within a list or from list to list.

Collection Vs Array Performance wise

Could you please let me know Performance wise why Array is better than Collection?
It is not. It will actually depend on the use you make of your container.
Some algorithms may run in O(n) on an array and in O(1) on another collection type (which implements the Collection interface).
Think about removal of an item for instance. In that case, the array, even if a native type, would perform slower than the linked list and its method calls (which could be inlined anyway on some VMs): it runs in O(n) VS O(1) for a linked list
Think about searching an element. It runs in 0(n) for an array VS O(log n) for a tree.
Some Collection implementations use an array to store their elements (ArrayList I think) so in that case performance will not be significantly different.
You should spend time on optimizing your algorithm (and make use of the various collection types available) instead of worrying of the pros/cons of an array VS Collection.
Many collections are wrappers for arrays. This includes ArrayList, HashMap/Set, StringBuilder. For optimised code, the performance difference of the operations is minimal except when you come to operations which are better suited to that data structure e.g. lookup of a Map is much faster than the lookup in an array.
Using generics for collections which are basically primitives can be slower, not because the collection is slower but the extra object creation and cache usage (as the memory needed can be higher) This difference is usually too small to matter but if you are concerned about this you can use the Trove4J libraries which are wrappers for arrays of primitives instead of arrays of Objects.
Where collections are slower is when you use operations which they are not suitable for e.g. random access of a LinkedList, but sensible coding can avoid these situations.
Basically, because arrays are primitive data structures in Java. Accesses to them can be translated directly into native memory-access instructions rather than method calls.
That said, though, it's not entirely obvious that arrays will strictly outperform collections in all circumstances. If your code references collection variables where the runtime type can be monomorphically known at JIT-time, Hotspot will be able to inline the access methods, and where they are simple, can be just as fast since there's basically no overhead anyway.
Many of the collections' access methods are intrinsically more complex than array referencing, however. There is, for instance, no way that a HashMap will be as efficient as a simple array lookup, no matter how much Hotspot optimizes it.
You cannot compare the two. ArrayList is an implementation, Collection is an interface. There might be different implementations for the Collection interface.
In practice the implementation is chosen which as the simple access to your data. Usually ArrayList if you need to loop through all elements. Hashtable if you need access by key.
Performance should be considered only after measurements are made. Then it is easy to change the implementation because the collection framework has common interfaces like the Collection interface.
The question is which one to use and when?
An array is basically a fixed size collection of elements. The bad point about an array is that it is not resizable. But its constant size provides efficiency if you are clear with your element size. So arrays are better to use when you know the number of elements available with you.
Collection
ArrayList is another collection where the number of elements is resizable. So if you are not sure about the number of elements in the collection use an ArrayList. But there are certain facts to be considered while using ArrayLists.
ArrayLists is not synchronized. So if there are multiple threads
accessing and modifying the list, then synchronization might be
required to be handled externally.
ArrayList is internally implemented as an array. So whenever a new
element is added an array of n+1 elements is created and then all the
n elements are copied from the old array to the new array and then
the new element is inserted in the new array.
Adding n elements requires on time.
The isEmpty, size, iterator, set, get and listIterator operations
require the same amount of time, independently of element you access.
Only Objects can be added to an ArrayList
Permits null elements
If you need to add a large number of elements to an ArrayList, you can use the ensureCapacity(int minCapacity) operation to ensure that the ArrayList has that required capacity. This will ensure that the Array is copied only once when all the elements are added and increase the performance of addition of elements to an ArrayList. Also inserting an element in the middle of say 1000 elements would require you to move 500 elements up or down and then add the element in the middle.
The benefit of using ArrayList is that accessing random elements is cheap and is not affected by the number of elemets in the ArrayList. But addition of elements to the head of tail or in the middle is costly.
Vector is similar to ArrayList with the difference that it is synchronized. It offers some other benefits like it has an initial capacity and an incremental capacity. So if your vector has a capacity of 10 and incremental capacity of 10, then when you are adding the 11th element a new Vector would be created with 20 elements and the 11 elements would be copied to the new Vector. So addition of 12th to 20th elements would not require creation of new vector.
By default, when a vector needs to grow the size of its internal data structure to hold more elements, the size of internal data structure is doubled, whereas for ArrayList the size is increased by only 50%. So ArrayList is more conservative in terms of space.
LinkedList is much more flexible and lets you insert, add and remove elements from both sides of your collection - it can be used as queue and even double-ended queue! Internally a LinkedList does not use arrays. LinkedList is a sequence of nodes, which are double linked. Each node contains header, where actually objects are stored, and two links or pointers to next or previous node. A LinkedList looks like a chain, consisting of people who hold each other's hand. You can insert people or node into that chain or remove. Linked lists permit node insert/remove operation at any point in the list in constant time.
So inserting elements in linked list (whether at head or at tail or in the middle) is not expensive. Also when you retrieve elements from the head it is cheap. But when you want to randomly access the elements of the linked list or access the elements at the tail of the list then the operations are heavy. Cause, for accessing the n+1 th element, you will need to parse through the first n elements to reach the n+1th element.
Also linked list is not synchronized. So multiple threads modifying and reading the list would need to be synchronized externally.
So the choice of which class to use for creating lists depends on the requirements. ArrayList or Vector( if you need synchronization ) could be used when you need to add elements at the end of the list and access elements randomly - more access operations than add operations. Whereas a LinkedList should be used when you need to do a lot of add/delete (elements) operations from the head or the middle of the list and your access operations are comparatively less.

Is an ArrayList the same thing as a singly-linked list?

In Java, I have been asked to store integer values in a singly-linked list and then print the elements stored in the list. Here is what I came up with:
int max = 10;
List<Integer> list = new ArrayList<Integer>();
for (int num = 0; i < max; i++){
list.add(num);
}
System.out.print(list);
I was wondering, is ArrayList the same thing as a singly-linked list? I want to make sure that I'm answering the question correctly. Does this make sense? Thanks!
No - ArrayList is not a linked list at all - it's an array list. ArrayList stores its elements in an array, whereas linked lists store them in arbitrary memory by linking objects together.
LinkedList is a doubly-linked list, and I'm sure that there are various singly linked list implementations you could grab, but given that this is an assignment you'll either be marked down or fail outright if you try to hand in code using someone else's implementation.
Instead, find an article etc. which describes linked lists and try to implement one yourself.
Generally these are built in java by having a class SomeClass containing a forward link of type SomeClass and a value. You build the list by linking each SomeClass instance to the next through the forward link.
No ArrayList is definitely not the same as a singly linked list. In fact, it is not a linked list at all: it is a list that uses an array for its backing storage. This lets you access ArrayList in arbitrary order, as opposed to linked lists, that must be accessed sequentially.
Java library has a doubly-linked list, but no singly-linked one; you need to write it yourself.
There are several good implementations available on the internet; take a look at this answer on the codereview site to gain some ideas on how to implement a singly linked list of your own.
No, ArrayList is an implementation of the List interface that uses a backing array to store the data. It sounds like the assignment wants you to write your own singly-linked List implementation.
No, an ArrayList is backed by an array. Arrays utilize contiguous storage (that is, the start of the array + offset of size of whatever is stored in the array == next element). Java has a LinkedList class, however, this is a doubly linked list, meaning that it contains two references: one to the previous element, and one to the next element.
Java does not have a singly linked list as a built in data structure. Either the question is asking you write your own implementation of a singly linked list, or is incorrect when it says to use one.
The name "Array"List states that the underlying implementation uses "arrays" for management. Whenever we talk about "Linked"List we are actually thinking about "Noded" lists i.e. every element has got a pointer to the forward node (and previous node if doubly-linked list). At least that's what this DSA book (by Granville Barnett and Luca Del Tongo) is saying.
In commercial Life your Solution is Perfect, but unfortunately ist seems that you are requested to use a Single linkes List which in Std Java does Not exist.
(And would Not make much sense)
For Purpos of Training you have to Write your own List.

java - what is the difference between a list and an arraylist [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a List vs. an ArrayList?
Ive used both of them, but im just wondering what are the pros and cons between them? What are the major differences? And which one is better to use?
Thanks.
List is an interface implemented by ArrayList class. Another well-known implementation of the List is LinkedList.
ArrayList provides constant-time random access, while LinkedList provides constant time for non-sequential access. When you declare a variable that will hold an ArrayList, consider accessing it through an interface, like this:
List<ElementType> myList = new ArrayList<ElementType>();
This will let you swap in a different implementation without disturbing the rest of your code.
List merely describes the contract of what it means to be a list. As such, it is not a concrete implementation but merely an interface. A list can be implemented in a number of ways.
In particular, you have ArrayList, which internally keeps a dynamic array for storing all the elements in order. You also have LinkedList, which stores elements as a doubly linked list i.e. a sequence of nodes which keep references to the previous and next nodes.
Vector is another List, much like an ArrayList in that its implementation is based on a dynamic array; it's, however, a relic of the older versions of Java and is guaranteed to be thread-safe by being wholly synchronized. In practice, new Vector<T>() is more-or-less equivalent to Collections.synchronizedList(new ArrayList<T>()).
The reason for having a List is that a list can come implemented in a number of ways. That being said, often you want to have some sort of generic behavior that can be applicable to all Lists... see polymorphism.
A List is an interface, and an ArrayList is an implementation of that interface. An ArrayList is a List, and so are LinkedLists, Stacks, Vectors, etc.
the other posters already answered the "what" part of your question. Some considerations to think about when choosing between them.
An ArrayList uses an array behind the scenes. So accessing by index can be done in constant time. Adding can also be done in constant time, if the array has been allocated with enough space. However, when the space runs out, ArrayList will allocate a larger array and copy the old array values into the new one.
A LinkedList uses nodes that are chained together. Accessing by an index can potentially require walking the entire list (linear time). Inserting only requires creating a new node and adding it at the end (which could be constant time if a tail pointer is maintained).
So "which one is better" can depend on how you are using it. Truthfully, I've never measured performance differences between the two, but it's just something to consider.

Confusing point in List documentation

I am not clear on a point in the documentation of List.
It says:
i) Note that these operations may execute in time proportional to the
index value for some implementations (the LinkedList class, for
example).
ii) Thus, iterating over the elements in a list is typically
preferable to indexing through it if the caller does not know the
implementation.
Note that I put the (i) and (ii) in the quote.
Point (i) is pretty obvious due to the way we access a linked list vs the random access of an array.
I can not understand point (ii) though.
What do we gain by prefering an iterator if we don't know the implementation?
I mean if the implementation is a LinkedList is there any difference in the performance than accessing via the index?
I imagine not, since the Iterator would be manipulating a LinkedList anyway.
So there would be no difference.
So what is the meaning of the recommendation of (ii) in the doc?
The iterator of a linked list can just have a pointer to the next node in the list, and go to the next node each time next() is called. It doesn't start from the beginning every time. Whereas if you use an index and call get(i), the linked list has to iterate from the beginning until the ith element at each iteration.
What you missed is that the iterator implementation of an ArrayList and the one of a LinkedList are completely different.
No, if the implementation is a LinkedList then an iterator will be much more efficient - O(n) for iterating over the whole list instead of O(N2). As the iterator is provided by the list, it has access to the internal data structures. It can just keep a reference to "the current node" making it a constant time operation to get to the next one: just follow the link!
(If you're still confused, I suggest you just look at the implementation - that's likely to make it clearer.)

Categories