I just noticed that Stack extends Vector in Java, ref: here.
Vector is slower than ArrayList so is there a better Stack I can use?
Thanks.
java.util.ArrayDeque has all stack methods (pop, push, peek) and it is fast. API This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.
You can use Apache's ArrayStack that is based on ArrayList instead of Vector:
http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections/ArrayStack.html
I find that LinkedList does a good job when you only need to access the front (and back) of a data structure. It adds with complexity O(1) and gets from the front also with O(1). It also never has to worry about resizing the backing array.
Related
I notice that linkedList has some methods like pop and push. Typically, if I want to use the feature of stack (FILO).Would the linkedList be the best choice?
LinkedList will work, and in fact implements the most stack-like interface in the JDK, Deque.
ArrayDeque is the other main non-threadsafe implementation, and is probably more efficient if you only need the stack operations. The above link for Deque lists the other two JDK-provided implementations, which are thread safe.
There is no better or worse approach to implement a stack but they have different advantages.
Implementation based on linked list gives you more flexibility over the container's capacity since you can theoretically always add more elements to it. Array based stack is more limited in terms of capacity. Linked list implicate more space overhead though, as you need to store references to other nodes.
Performance wise with a stack you only access the top element which means you don't need the random access feature that an array gives you over linked lists.
I have to write a stack for class and while I understand the concept of how a stack works, I wasn't told if they are made using an array or a linked list or something else? How are most stacks created?
ArrayDeque is a solid class implementation of the stack concept. This class has implemented stack in the most efficient way. Please look at the class implementation for the details of various methods.
http://www.docjar.com/html/api/java/util/ArrayDeque.java.html
More specifically, look at public E pollFirst(){...} and public void addFirst(E e)
java.util.Stack is a subclass of java.util.Vector which was a Thread-safe precursor to ArrayList. Hope that helps.
Both options, array and linked list are appropiate.
A linked list may be simpler because you needn't worry about the array size. An array based implementation on the other hand may have better runtime behavior and can be easier to debug (because its easier to view the array than a linked list in the debugger).
Chose whatever you're comfortable with.
What is the fastest collection in Java?
I only need the operations to add and remove, order is not important, equals elements is not a issue, nothing more than add and remove is imporant.
Without limit size is important too.
These collection will have Objects inside him.
Currently I'm using ArrayDeque because I see this is the faster Queue implementation.
ArrayDeque is best. See this benchmark, which comes from this blog post about the results of benchmarking this. ArrayDeque doesn't have the overhead of node allocations that LinkedList does nor the overhead of shifting the array contents left on remove that ArrayList has. In the benchmark, it performs about 3x as well as LinkedList for large queues and even slightly better than ArrayList for empty queues. For best performance, you'll probably want to give it an initial capacity large enough to hold the number of elements it's likely to hold at a time to avoid many resizes.
Between ArrayList and LinkedList, it seems that it depends on the average number of total elements the queue will contain at any given time and that LinkedList beats ArrayList starting at about 10 elements.
You can use a java.util.LinkedList - it's doubly-linked and cicrular, so adding to one end and taking from the other are O(1)
Whatever implementation you choose, refer to it by the Queue interface, so that you can easily change it if it turns out not to fit your case (if, of course, a queue is what you need in the first place)
Update: Colin's answer shows a benchmark that concludes that ArrayDeque is better. Both have O(1) operations, but LinkedList creates new objects (nodes), which slightly affect performance. Since both have O(1) I don't think it would be too wrong to choose LinkedList though.
ConcurrentLinkedDeque is the best choice for multi thread Queue
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.
i am C++ person don't know much Java
Well, Vector class shouldn't be used. There are so many containers available in Java. Few of them:
ArrayList is good for random access, but is bad for inserting or removing from the middle of the list.
LinkedList is bad for random access, but is fair good for iterating and adding/removing elements from the middle of container.
You can use ArrayList instead of vector in Java.
Check out this article:
http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-0622-vector.html
LinkedList can add/remove items at O(1)
First of all, Vector removal time complexity is O(n) not O(n^2). If you want more performant class, you should choose LinkedList. Its time complexity is constant.
Maybe a list is not the ideal data structure for your use case - would you be better off using a HashSet if the ordering of elements is not imporant?
Actually, the difference between Vector and ArrayList is that Vector is synchronized whereas ArrayList is not. Generally, you don't need synchronization and thus you'd use ArrayList (much like StringBuffer <-> StringBuilder).
The replacement mostly depends on how you intend to use the collection.
Adding objects to an ArrayList is quite fast, since if more space is required, it is normally doubled, and if you know the size requirements in advance, even better.
Removing from an ArrayList is O(n) but iteration and random access are fast.
If you have frequent add or remove operations and otherwise iterate over the list, a LinkedList would be fine.
You could even consider using a LinkedHashMap which allows fast access as well as preserves the order of insertion.
i think, Vector using System.arrayCopy which complexity is O(n^2)
It is correct that Vector will use System.arrayCopy to move the elements. However the System.arrayCopy() call copies at most Vector.size() elements, and hence is O(N) where N is the vector's size.
Hence O(N^2) is incorrect for a single insertion / removal.
In fact, if you want better than O(N) insertion and deletion, you will need to use some kind of linked list type with a cursor abstraction that allows insertion and deletion at "the current position". Even then you only get better than O(N) if you can do the insertions / deletions in the right order; i.e. not random order.
FWIW, the Java List APIs don't provide such a cursor mechanism ... not least because it would be awkward to use, and only efficient in certain circumstances / implementations.
Thanks to everyone for there contribution which helped me to solve this problem. I used a circular queue which has been written with help of vector.
For a programming class I am creating a blackjack program for the first homework assignment. The professor has given us a sample Card class, which includes the method to add them to a deck. For her deck, she uses an ArrayList, which you can easily Knuth Shuffle with the Collections.shuffle() method.
That method does not work for Stacks though (obviously), but I think a Stack structure would work best for this program because you may pop and push cards into and out of the deck.
Both java.util.ArrayList<E> and java.util.stack<E> implement the java.util.List<E> interface, and Collections.shuffle() takes a java.util.List<?> as a parameter. You should be able to pass a Stack into Collections.shuffle(), unless you're using a different stack implementation that does not implement java.util.list<E>. If you are, I would advise you to switch to a different stack implementation.
I guess it's much easier to do stack operations on an ArrayList.
A stack is a list, so you can call Collections.shuffle() on your stack.
That said, Stack is an old class, like Vector and kind of outmoded. Nowadays you would use a Dequeue (a double ended queue which works as either a queue or a stack) rather then a stack but, Dequeues are not lists, so they can't be shuffled.
Also, you can always put your cards in a List, shuffle them, and then add all of them to a Dequeue
There is no reason why a stack structure should not be random access as well (java.util.Stack does, although that has problems of its own). Other than that, you can pop the elements of the stack into an ArrayList, shuffle and then push them back on to your stack.
No, Fisher-Yates shuffle relies on random access to the dataset. You need some Collection which allows get(int index). If you need a stack just use a list. push and pop just call get(0) and add(0). This is better than implementing some custom stack class. Use what you have, don't invent new classes.
Adam's answer is best for a stack. For card games, what I usually use is a simple arraylist and remove random elements. No shuffling required.
Just shuffle before/as you put the cards onto the stack.
Since a properly implemented Knuth shuffle does not allow replacement of cards in the part of the deck already traversed you can simply place them onto the stack as you go along...
Since java will not let you treat a stack as a random access list just copy from the stack into an ArrayList to do the shuffling phase (an extra 52 element ArrayList knocking around is no big deal)
the Collections.shuffle() method does that for you you dont have to explicitly.
"If the specified list does not implement the RandomAccess interface and is large, this implementation of shuffle() dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place."
this is what the java documentation says about Collections.shuffle() method implementation
so passing a java.util.Stack (an implementation of java.util.List interface) should work...