Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implementation for stack

Is there a class in Java that implements the concept of Stack form the data structure books, means LIFO, pop is O(1) and push in O(1)?

I read a bit the code of java.util.Stack and it is doesn't seems that push is O(1) - push can call Vector.grow() and it can take O(n) ( I know it amortized O(1) but I looking for always push in O(1) )

And I want to understand why java.util.Stack was designed as is, not as the theoretical principle of stack

like image 757
Matan Wiesner Avatar asked Mar 04 '23 18:03

Matan Wiesner


1 Answers

ArrayDeque is preferable to LinkedList.

Because it is backed by an array, rather than storing the individual elements in separate node instances, it is far more performant.

According to Josh Bloch, author of LinkedList, in tweets:

Does anyone actually use LinkedList? I wrote it, and I never use it.

and

ArrayDeque makes a great stack, queue, or deque

like image 117
Andy Turner Avatar answered Mar 10 '23 10:03

Andy Turner