Класс Stack
Современные программисты сейчас практически не используют Stack, который слишком прост и не очень гибок. Тем не менее, изучить его стоит, может именно он вам и пригодится.
Stack является подклассом класса Vector, который реализует простой механизм типа «последний вошёл — первый вышел» (LIFO). Можно представить процесс в виде детской пирамидки, когда вы по одному нанизываете диск на колышек. И снять диски вы сможете только по порядку, начиная с верхнего.
Взять элемент, который положили первым, вам никто не позволит. Даже не пытайтесь сделать так.
Напишем простейший пример применения стека.
Метод push() помещает объект в стек, а метод pop(), наоборот, вытаскивает объект из стека.
Пример с числами слишком скучный. Давайте позовём на помощь котов. Создадим простой класс Cat:
Представьте себе, что имеется длинная узкая труба, запаянная с одного конца. Мы заталкиваем в трубу пушистого друга, поэтому метод называется «пуш» (push()). А чтобы вытащить кота, хватаем его за попу (метод pop()). Давайте запихаем в трубу трёх котов, а потом вытащим их.
У нас есть три кота — Барсик, Мурзик и Васька. В такой последовательности мы их запихнули в трубу и проверяем текущий стек.
Вызываем метод pop() первый раз. Как видите, мы не указываем позицию элемента, так стек работает только с последним элементом. Последним был Васька. Чтобы узнать, кто теперь последний в стеке, не удаляя его оттуда, нужно вызвать метод peek().
Повторяем этот шаг ещё раз и вытаскиваем кота Мурзика. Затем и Барсика.
Чтобы убедиться, что в трубе никого не осталось, вызываем метод empty(), который возвращает булево значение.
Если при пустом стеке вызвать методы pop() или peek(), то программа закроется с ошибкой. Чтобы избежать подобной ситуации, нужно обработать исключение EmptyStackException. Тогда программа будет работать без сбоев.
В конце выводим информацию о пустом стеке.
У класса также есть метод int search(Object o), который ищет заданный элемент в стеке, возвращая количество операций pop(), которые требуются для того чтобы перевести искомый элемент в вершину стека. Если заданный элемент в стеке отсутствует, этот метод возвращает -1.
Надеюсь, вы поняли что такое стек. Пожалуйста, не загоняйте котов в трубу.
Источник
Класс Stack в Java
Класс стека в Java является частью платформы Collection, которая упрощает различные операции, такие как push, pop и т. д.
Что такое класс Stack в Java?
Класс Stack в Java – это структура данных, которая следует за LIFO (Last In First Out). Java Stack Class подпадает под базовую платформу Collection Hierarchy Framework, в которой вы можете выполнять базовые операции, такие как push, pop и т. д.
Мы знаем, что инфраструктура Java collection включает в себя интерфейсы и классы. Теперь давайте разберемся, как этот класс организован в иерархии инфраструктуры коллекций Java.
В приведенной выше иерархии синий прямоугольник относится к различным интерфейсам, а желтый прямоугольник определяет класс. Стек в Java расширяет векторный класс, который дополнительно реализует интерфейс List. Всякий раз, когда вы создаете стек, изначально он не содержит какого-либо элемента, т. е. Стек пуст.
Методы
В Java в основном существует 5 методов класса стека.
Метод | Описание |
empty() | Проверяет, пуст ли стек |
push() | Ставит элемент в верх стека |
pop() | Удаляет объект из стека |
peek() | Рассматривает объект стека, не удаляя его |
search() | Поиск элемента для получения его индекса |
Давайте разберемся с каждым из этих методов на программном примере:
Empty stack: []
push(4)
Current Stack: [4]
push(8)
Current Stack: [4, 8]
push(9)
Current Stack: [4, 8, 9]
Element on stack top: 9
Element not found
Element is found at position 3
pop = 9
Remaining stack: [4, 8]
pop = 8
Remaining stack: [4]
pop = 4
Remaining stack: []
pop = empty stack
Объяснение: В приведенной выше Java-программе я сначала напечатал пустой стек и добавил несколько элементов, используя метод Push. Как только элементы присутствуют в стеке, я отобразил элементы сверху стека, используя метод Peek.
После этого я выполнил поиск с использованием метода Search и, наконец, удалил элементы в классе Java Stack с помощью метода Pop.
Размер стека
Вывод: Is the Java Stack empty? false
Size of Stack : 3
Перебор элементов стека на Java
- Итерация по стеку с использованием iterator()
- Перебор стека с использованием Java 8 forEach()
- Перебор стека с использованием listIterator() сверху вниз
Давайте начнем перебирать элементы с помощью iterator().
Точно так же вы можете выполнить итерацию другими методами.
Вывод: итерация стека с помощью forEach():
Итерация с использованием listIterator() сверху вниз:
Объяснение: В приведенном выше коде вы можете увидеть итерацию с помощью метода forEach(), а затем повернуть ее с помощью listIterator() сверху вниз в стеке.
Средняя оценка / 5. Количество голосов:
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
Источник
Stack Class
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
The Stack class represents a last-in-first-out (LIFO) stack of objects.
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
Creates an empty Stack.
A constructor used when creating managed representations of JNI objects; called by the runtime.
Properties
How many elements should be added to the vector when it is detected that it needs to grow to accommodate extra entries.
(Inherited from Vector)
Returns the runtime class of this Object .
(Inherited from Object)
The number of elements or the size of the vector.
(Inherited from Vector)
The elements of the vector.
(Inherited from Vector)
The handle to the underlying Android instance.
(Inherited from Object)
(Inherited from AbstractCollection)
The number of times this list has been structurally modified.
(Inherited from AbstractList)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
(Inherited from AbstractList)
(Inherited from AbstractCollection)
(Inherited from AbstractCollection)
(Inherited from AbstractList)
Adds the specified component to the end of this vector, increasing its size by one.
(Inherited from Vector)
Returns the current capacity of this vector.
(Inherited from Vector)
(Inherited from AbstractCollection)
Returns a clone of this vector.
(Inherited from Vector)
(Inherited from AbstractCollection)
(Inherited from AbstractCollection)
Copies the components of this vector into the specified array.
(Inherited from Vector)
Returns the component at the specified index.
(Inherited from Vector)
Returns an enumeration of the components of this vector.
(Inherited from Vector)
Tests if this stack is empty.
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
(Inherited from Vector)
Indicates whether some other object is «equal to» this one.
(Inherited from Object)
Returns the first component (the item at index 0 ) of this vector.
(Inherited from Vector)
Returns the element at the specified position in this Vector.
(Inherited from Vector)
Returns a hash code value for the object.
(Inherited from Object)
(Inherited from AbstractList)
Returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
(Inherited from Vector)
Inserts the specified object as a component in this vector at the specified index .
(Inherited from Vector)
Returns an iterator over the elements in this list in proper sequence.
(Inherited from AbstractList)
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
(Inherited from Object)
Returns the last component of the vector.
(Inherited from Vector)
(Inherited from AbstractList)
Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
(Inherited from Vector)
(Inherited from AbstractList)
(Inherited from AbstractList)
Wakes up a single thread that is waiting on this object’s monitor.
(Inherited from Object)
Wakes up all threads that are waiting on this object’s monitor.
(Inherited from Object)
Looks at the object at the top of this stack without removing it from the stack.
Removes the object at the top of this stack and returns that object as the value of this function.
Pushes an item onto the top of this stack.
(Inherited from AbstractList)
(Inherited from AbstractCollection)
(Inherited from AbstractCollection)
Removes all components from this vector and sets its size to zero.
(Inherited from Vector)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
(Inherited from Vector)
Deletes the component at the specified index.
(Inherited from Vector)
Removes from this list all of the elements whose index is between fromIndex , inclusive, and toIndex , exclusive.
(Inherited from AbstractList)
(Inherited from AbstractCollection)
Returns the 1-based position where an object is on this stack.
(Inherited from AbstractList)
Sets the component at the specified index of this vector to be the specified object.
(Inherited from Vector)
Sets the Handle property.
(Inherited from Object)
Sets the size of this vector.
(Inherited from Vector)
Returns the number of components in this vector.
(Inherited from Vector)
Creates a (Inherited from Vector)
(Inherited from AbstractList)
(Inherited from AbstractCollection)
(Inherited from AbstractCollection)
Returns a string representation of the object.
(Inherited from Object)
Trims the capacity of this vector to be the vector’s current size.
(Inherited from Vector)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.
(Inherited from Object)
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
Performs an Android runtime-checked type conversion.
Источник