![]() On the other hand, it takes linear time to find an element, given its index. Linked lists allow insertion and removal of elements at arbitrary positions in constant time. In a stack, we only ever append to or remove from the end which makes an ArrayList much more appealing to implement a stack.”, I would like to expand on that. Late Update: Since I'm getting down-votes for the statement that “Linked lists are good for inserting and removing elements at random positions. On the other hand Stack implements List which should be considered questionable. LinkedList implements Deque which is correct since a Deque requires elements can be added and removed from / to the beginning or end and LinkedList qualifies for this by offering insertion and deletion at random positions. ![]() Note that the inheritance relation between List and the newer Deque interface is more consistent than between List and Stack. (This is not what does which brings us back to the quote from the docs.) For example, we could implement Stack by simply delegating to ArrayList but provide a type that clearly says in its name what its meant to be and does not provide operations (like random access) that might violate the concept of a stack. If a certain use-pattern occurs particularly frequent, we might decide to add another class that refers to this pattern in its name which will make the code better structured.We provide one or more implementations of that interface that must all provide the required functionality but may be optimized for a certain use case (eg ArrayList or LinkedList).We define a set of operations in an interface (eg List).In a stack, we only ever append to or remove from the end which makes an ArrayList much more appealing to implement a stack.Īt this point, we realize that ArrayList and LinkdList both provide the functionality of a List which brings us close to the heart of good object oriented design: Linked lists are good for inserting and removing elements at random positions. While a LinkedList provides all the operations that are needed to make a stack, it will perform poorly. Second, “providing the same functionality” is not a good measure to gauge whether a class should be there or not. Which tells us that the Stack class is mostly a leftover that has become more or less redundant with the newer Java Collections Framework. First, in the introduction of Stack's documentation it says:Ī 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. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |