Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I wanted to know why Stack is implemented using Vector and not with LinkedList. As far as I know, LinkedList provides more efficient structure for deletion and insertion of elements. So, why stack is implemented using vector and not LinkedList. Java implements Queue interface with LinkedList and since in both stack and queue, insertion and deletion is the primary function, why not linkedlist for Stack.
Stack and Vector are both old classes.
If you read the Javadoc of Stack, you'll see that it suggests using Deque instead:
A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.
And LinkedList does implement the Deque interface.
As far as I know, LinkedList provides more efficient structure for deletion and insertion of elements.
That is not actually true ... in the context of stack operations. (Or in general).
A Vector is a form of array list. It works by allocating an array to hold a number of elements, and using array indexing to access and update the list. Insertion and deletion at a random position in the Vector is expensive because it entails copying multiple element references.
However, that not what a Stack requires. It actually requires insertion and deletion exclusively at the end of the Vector, and that is cheap. In most cases, insertion and deletion simply involves assigning an element into an array cell and adjusting the Vector object's length field. It only gets expensive if there is not enough space in the array. Then the array has to be "grown" by creating a new one and copying the elements. But when an array list grows the array exponentially (e.g. by doubling its size), the math says that the amortized cost is O(1) over the lifetime of the array list.
By contrast, every time you insert an element into a LinkedList, it involves allocating a new internal "node" object to hold the element. That is more expensive on average than a Vector insertion, especially when you take into account the GC costs incurred over the lifetime of the "node" object.
It also turns out a LinkedList uses up to 4 times as much memory per element as a Vector does, assuming we are using 64 bit references.
In short, a Vector is more efficient and uses less space than a LinkedList for a stack data structure. The correct design choice was made1.
1 - As you would expect. We can assume that the engineers who designed and maintained Java over the last ~25 years knew what they were doing. Or that the tens of thousands of other people who have looked at that code since it was written would also have noticed a (hypothetical!) mistake of that magnitude and logged a bug report.
Related
This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 10 months ago.
I really don't see how linked lists are better than array , the insertion and deletion complexities are same , eg. , In array the insertion at rear is O(1) while for linked lists the insertion at head is O(1) , and simillarly insertion in arrays at front is O(n) but for the later it is O(n) to insert at the rear end.
Apart from the only fact that linked lists are dynamic in nature ,I dont see any benefits of linked lists over arrays. Moreover , I can use a dynamic array to counter that problem.
Again Array also have better results when we want to access an element.
So can anybody please tell me why are linked lists better than array? And if they are not better , then why do we use it?
No data structure is universally better than another data structure. There are benefits and drawbacks and which is better depends on what benefits and drawbacks are more important for your use case.
the insertion and deletion complexities are same
Firstly, it isn't possible to insert or delete elements of arrays at all. Their size remains constant. But I'll assume that you meant "dynamic array" data structure i.e. std::vector and java.util.ArrayList (not to be confused with dynamically allocated array which is also called "dynamic array").
The insertion and deletion complexities between linked lists and dynamic array are not the same.
but for the later it is O(n) to insert at the rear end.
Given a an iterator to a linked linked list, you can insert after the pointed element in constant time. Hence, if you maintain an iterator to the end of the list, you can insert there in constant time.
An important advantage of linked list over the dynamic array, besides the complexity, is that the elements remain stable in memory. In vector, if adding an element exceeds the capacity, then all iterators and references to existing elements are invalidated. Iterators as well as references to linked list elements remain valid until the element is erased. If you need this property, then using a dynamic array is not an option.
Linked lists, as independent data structures, are rarely used.
Quite often, however, objects are linked into a list by incorporating next and maybe prev pointers directly into the objects themselves. As a data structure, that is often referred to as an "intrusive" linked list.
Sometimes this is used to add features to existing data structures. In Java you can see this in LinkedHashMap, which links the map entries together into a list, preserving their insertion or access order and allowing you to use it as an LRU cache. Similarly, leaf nodes in a B+tree are often linked onto a list to simplify traversal. There are many examples.
This question already has answers here:
When to use LinkedList over ArrayList in Java?
(33 answers)
Closed 8 years ago.
I see that there are a ton of generic data structures provided in Java. They all implement List, so they can be used almost interchangeably, but when would I want to use each? Personally, I stick to LinkedList because it's something I'm "familiar" with. I'm not asking for an explanation of every single structure, but can you explain some of the more common ones and give their uses, as well as compare and contrast the uses of "Vector-like" structures?
It depends on the performance characteristics and behavior you are looking for.
For example in a LinkedList add, delete, and retrieve are O(1), O(1), and O(n), whereas for an ArrayList, the same operations are O(n), O(n), and O(1) if using get(int) and O(n) if using get(Object). However ArrayList uses less memory than LinkedList per entry.
One often uses Vector<type> to add elements to the structure that are part of the same collection, but do not have any relationship to other members (other than being part of the same collection). A LinkedList indicates that there is some sort of ordering that is important among the members of the collection.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to understand which is faster in accessing elements from collections in Java like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap etc.
From this question: Suitable java collection for fast get and fast removal, I got to know that ArrayList takes O(1) and TreeMap as O(log n)
where as this: Map/ArrayList: which one is faster to search for an element shows that ArryList is O(n), HashMap as O(1) and TreeMap as O(log n)
where as this: Why is it faster to process a sorted array than an unsorted array? says that sorted array is faster than unsorted array. As the elements in TreeMap are sorted then can I assume all sorted collections are faster than un-sorted collections?
Please help me in understanding which is faster to use in accessing elements from java collections of list, set, map etc implementations.
Every collection type is suitable for a particular scenario. There is no fastest or best collection.
If you need fast access to elements using index, ArrayList is your answer.
If you need fast access to elements using a key, use HashMap.
If you need fast add and removal of elements, use LinkedList (but it has a very poor index access performance).
and so on.
It depends whether you want to access an element as index based(in case of list) or see if an Object exists in the Collection
If you want to access an element index based,then arraylist is faster as it implements RandomAccess Marker interface and is internally backed by an array.
Sets are internally backed by Map ,so performance of Map and Set is same(Set use a dummy Object as value in key-value pair).I would suggest you to use a HashSet.
The problem that many programmers dont notice is that performance of Hashset or HashMap is best O(1) when the hashing function of Key Object is good,ie. it produces different values for different Objects (though this is not a strict requirement).
NOTE :- If you are Hashing funciton is not good,it degrades to a LinkedList internally and its performance degrades to O(n)
My personal preference is to Use EnumMap or EnumSet.It simply uses the Enum values for its functioning and programmers dont have to worry about the Enum's hashcode/equals function.For rest other cases,use HashSet or HashMap(if you dont have to make it ordered)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Size-limited queue that holds last N elements in Java
Java - Ring Buffer
I am interested in a bounded above queue, that whenever faced with object insertion, would remove the oldest object first, if the insertion would result in 'overflowing'. I want the addition to be O(1) and the memory usage as little as possible. I was thinking about either overriding add method on LinkedList, but ideally I would implement a circular, array based list, with catching front/back pointer. Whenever the addition is made over capacity, front pointer advances, and then the back one. Is there an implementation similar to this?
A linked list is a waste of memory, since the next pointer uses mem, that the ArrayList does not.
The performant implementations are based on ArrayList or better on an array.
If your circular buffer size is fixed, you would use an array.
I implemented a circular buffer using an internal array, with start and end position index vars. I did not found an implemnetation of a circular list / buffer, that did that what i wanted.
It was not dificullt to implement, but i recomend using a high number of unit test cases, to prove that your circ buffer works as expected.
Maybe the title is not appropriate but I couldn't think of any other at this moment. My question is what is the difference between LinkedList and ArrayList or HashMap and THashMap .
Is there a tree structure already for Java(ex:AVL,red-black) or balanced or not balanced(linked list). If this kind of question is not appropriate for SO please let me know I will delete it. thank you
ArrayList and LinkedList are implementations of the List abstraction. The first holds the elements of the list in an internal array which is automatically reallocated as necessary to make space for new elements. The second constructs a doubly linked list of holder cells, each of which refers to a list element. While the respective operations have identical semantics, they differ considerably in performance characteristics. For example:
The get(int) operation on an ArrayList takes constant time, but it takes time proportional to the length of the list for a LinkedList.
Removing an element via the Iterator.remove() takes constant time for a LinkedList, but it takes time proportional to the length of the list for an ArrayList.
The HashMap and THashMap are both implementations of the Map abstraction that are use hash tables. The difference is in the form of hash table data structure used in each case. The HashMap class uses closed addressing which means that each bucket in the table points to a separate linked list of elements. The THashMap class uses open addressing which means that elements that hash to the same bucket are stored in the table itself. The net result is that THashMap uses less memory and is faster than HashMap for most operations, but is much slower if you need the map's set of key/value pairs.
For more detail, read a good textbook on data structures. Failing that, look up the concepts in Wikipedia. Finally, take a look at the source code of the respective classes.
Read the API docs for the classes you have mentioned. The collections tutorial also explains the differences fairly well.
java.util.TreeMap is based on a red-black tree.
Regarding the lists:
Both comply with the List interface, but their implementation is different, and they differ in the efficiency of some of their operations.
ArrayList is a list stored internally as an array. It has the advantage of random access, but a single item addition is not guaranteed to run in constant time. Also, removal of items is inefficient.
A LinkedList is implemented as a doubly connected linked list. It does not support random access, but removing an item while iterating through it is efficient.
As I remember, both (LinkedList and ArrayList) are the lists. But they have defferent inner realization.