Java objects on stack

Java Stack

The Java Stack class, java.util.Stack , is a classical stack data structure. You can push elements to the top of a Java Stack and pop them again, meaning read and remove the elements from the top of the stack.

The Java Stack class actually implements the Java List interface, but you rarely use a Stack as a List — except perhaps if you need to inspect all elements currently stored on the stack.

Please note, that the Java Stack class is a subclass of Vector, an older Java class which is synchronized. This synchronization adds a small overhead to calls to all methods of a Stack. Additionally, the Vector class uses several older (no longer recommended) parts of Java, like the Enumeration which is superseded by the Iterator interface. If you want to avoid these issues you can use a Java Deque as a stack instead.

Читайте также:  Get this thread java

Java Stack Tutorial Video

If you prefer video, I have a Java Stack tutorial video here: Java Stack Tutorial Video.

Java Stack Video Tutorial

Java Stack Basics

A Stack is a data structure where you add elements to the «top» of the stack, and also remove elements from the top again. This is also referred to as the «Last In First Out (LIFO)» principle. In contrast, a Java Queue uses a «First In First Out (FIFO)» principle, where elements are added to the end of the queue, and removed from the beginning of the queue.

Create a Stack

To use a Java Stack you must first create an instance of the Stack class. Here is an example of creating a Java Stack instance:

Create a Stack with a Generic Type

You can set a generic type on a Stack specifying the type of objects the Stack instance can contain. You specify the stack type when you declare the Stack variable. Here is an example of creating a Java Stack with a generic type:

The Stack created above can only contain String instances.

Using a generic type on your Stack instances is recommended as it simplifies your code (no casts needed when accessing objects on the Stack), and decreases the risk that you push an object of the wrong type on the Stack.

Push Element on Stack

Once you have a Java Stack instance, you can push elements to the top of the Stack . The elements you push onto the Stack must be Java objects. Thus, you actually push objects to the Stack .

You push elements onto a Java Stack using its push() method. Here is an example of pushing an element (object) onto a Java Stack :

Stack stack = new Stack(); stack.push("1");

This Java example pushes a Java String with the text 1 onto the Stack . The String 1 is then stored at the top of the Stack .

Pop Element From Stack

Once an element has been pushed onto a Java Stack , you can pop that element from the Stack again. Once an element is popped off the Stack , the element is removed from the Stack . The top element of the Stack is then whatever element that was pushed onto the Stack just before the element just popped.

You pop an element off a Java Stack using the pop() method. Here is an example of popping an element off a Stack using the pop() method:

Stack stack = new Stack(); stack.push("1"); String topElement = stack.pop();

Once an element is popped off a Stack , the element is no longer present on the Stack .

Peek at Top Element of Stack

The Java Stack class has a method called peek() which enables you to see what the top element on the Stack is, without popping off the element. Here is an example of peeking at the top of a Java Stack :

Stack stack = new Stack(); stack.push("1"); String topElement = stack.peek();

After running this Java example the topElement variable will contain the String object 1 which was pushed onto the Stack just before peek() was called. The String object is still present on the Stack after calling peek() .

Search the Stack

You can search for an object on the stack to get it’s index, using the search() method. The object’s equals() method is called on every object on the Stack to determine if the searched-for object is present on the Stack . The index you get is the index from the top of the Stack , meaning the top element on the Stack has index 1.

Here is how you search a Stack for an object:

Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); int index = stack.search("3"); //index = 3

Stack Size

You can obtain the size of a Java Stack, meaning the number of elements currently stored on the Stack, via the Stack size() method. Here is an example of obtaining the size of a Java Stack via its size() method:

Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); int size = stack.size();

After running this code the size variable will contain the value 3, since the Stack in the example contains 3 elements at the time its size() method is called.

Iterate Elements of Stack

You can iterate the elements of a Java Stack by obtaining a Java Iterator from the Stack . You obtain an Iterator by calling the Stack iterator() method. Here is an example of obtaining an Iterator from a Java Stack and iterating it:

Stack stack = new Stack(); stack.push(«123»); stack.push(«456»); stack.push(«789»); Iterator iterator = stack.iterator(); while(iterator.hasNext())

Process Stack Using Stream

It is also possible to process the elements on a Java Stack via the Java Stream API. You do so by first obtaining a Stream from the Stack via the stream() method.

Once you have obtained a Stream from the Stack , you can process the elements in the stream. Here is an example of obtaining a Stream from a Stack and processing the elements:

Stack stack = new Stack(); stack.push("A"); stack.push("B"); stack.push("C"); Stream stream = stack.stream(); stream.forEach((element) -> < System.out.println(element); // print element >);

Notice, that this example uses a Java Lambda as parameter to the Stream.forEach() method. The lambda just prints out the element to System.out

Reverse List Using Stack

You can use a Java Stack to reverse a Java List. You do so by pushing all the elements from the List onto the Stack , starting with the element with index 0, then 1 etc. Each element is removed from the List , then pushed onto the Stack . Once all the elements are on the Stack , you pop the elements off one by one and add them back to the empty list. Here is an example of reversing a Java List using a Java Stack :

List list = new ArrayList(); list.add("A"); list.add("B"); list.add("C"); System.out.println(list); Stack stack = new Stack(); while(list.size() > 0) < stack.push(list.remove(0)); >while(stack.size() > 0) < list.add(stack.pop()); >System.out.println(list);

Use a Java Deque as a Stack

As mentioned at the top of this Java Stack tutorial, you can use a Java Deque as a stack too. The Java Deque tutorial also shows how you can do that — but I will show you a short example here too:

Deque dequeAsStack = new ArrayDeque>String>(); dequeAsStack.push("one"); dequeAsStack.push("two"); dequeAsStack.push("three"); String one = dequeAsStack.pop(); String two = dequeAsStack.pop(); String three = dequeAsStack.pop();

As you can see, it looks pretty similar to using a regular Java Stack.

Stack Use Cases

A Stack is really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.

Источник

Class Stack

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty , and a method to search the stack for an item and discover how far it is from the top.

When a stack is first created, it contains no items.

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. For example:

 Deque stack = new ArrayDeque();

Field Summary

Fields declared in class java.util.Vector

Fields declared in class java.util.AbstractList

Constructor Summary

Method Summary

Methods declared in class java.util.Vector

Methods declared in class java.lang.Object

Methods declared in interface java.util.Collection

Methods declared in interface java.util.List

Constructor Details

Stack

Method Details

push

pop

peek

empty

Returns the 1-based position where an object is on this stack. If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at distance 1 . The equals method is used to compare o to the items in this stack.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java objects on stack

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty , and a method to search the stack for an item and discover how far it is from the top. When a stack is first created, it contains no items. 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. For example:

 Deque stack = new ArrayDeque();

Field Summary

Fields declared in class java.util.Vector

Fields declared in class java.util.AbstractList

Constructor Summary

Method Summary

Methods declared in class java.util.Vector

Methods declared in class java.lang.Object

Methods declared in interface java.util.Collection

Methods declared in interface java.util.List

Constructor Detail

Stack

Method Detail

push

pop

peek

empty

search

Returns the 1-based position where an object is on this stack. If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at distance 1 . The equals method is used to compare o to the items in this stack.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью