Stack applications in java

Stack Class in Java

Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.

The below diagram shows the hierarchy of the Stack class:

Stack Class in Java

The class supports one default constructor Stack() which is used to create an empty stack.

Declaration:

public class Stack extends Vector

All Implemented Interfaces:

  • Serializable: It is a marker interface that classes must implement if they are to be serialized and deserialized.
  • Cloneable: This is an interface in Java which needs to be implemented by a class to allow its objects to be cloned.
  • Iterable: This interface represents a collection of objects which is iterable — meaning which can be iterated.
  • Collection: A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired.
  • List:The List interface provides a way to store the ordered collection. It is a child interface of Collection.
  • RandomAccess: This is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.

How to Create a Stack?

In order to create a stack, we must import java.util.stack package and use the Stack() constructor of this class. The below example creates an empty Stack.

Here E is the type of Object.

Java

Pop Operation: 4 3 2 1 0 Element on stack top: 4 Element is found at position: 3 Element not found

Performing various operations on Stack class

1. Adding Elements: In order to add an element to the stack, we can use the push() method. This push() operation place the element at the top of the stack.

Java

[4, All, Geeks] [Geeks, For, Geeks]

2. Accessing the Element: To retrieve or fetch the first element of the Stack or the element present at the top of the Stack, we can use peek() method. The element retrieved does not get deleted or removed from the Stack.

Java

Initial Stack: [Welcome, To, Geeks, For, Geeks] The element at the top of the stack is: Geeks Final Stack: [Welcome, To, Geeks, For, Geeks]

3. Removing Elements: To pop an element from the stack, we can use the pop() method. The element is popped from the top of the stack and is removed from the same.

Читайте также:  Функция распределения хи квадрат питон

Java

Initial Stack: [10, 15, 30, 20, 5] Popped element: 5 Popped element: 20 Stack after pop operation [10, 15, 30]

Example

In Java, the Stack class is a subclass of the Vector class and represents a last-in-first-out (LIFO) stack of objects. It extends the Vector class to allow for easy implementation of the stack data structure.

Here’s an example of how you can use the Stack class in Java:

Java

In this example, we first import the Stack class from the java.util package. We then create a new Stack object called stack using the default constructor. We push four integers onto the stack using the push() method. We then pop the elements from the stack using the pop() method inside a while loop. The isEmpty() method is used to check if the stack is empty before attempting to pop an element.

This code creates a stack of integers and pushes 4 integers onto the stack in the order 1 -> 2 -> 3 -> 4. We then pop elements from the stack one by one using the pop() method, which removes and returns the top element of the stack. Since the stack follows a last-in-first-out (LIFO) order, the elements are popped in the reverse order of insertion, resulting in the output shown above.

The Stack class provides several other methods for manipulating the stack, such as peek() to retrieve the top element without removing it, search() to search for an element in the stack and return its position, and size() to return the current size of the stack. The Stack class also provides several constructors for creating a stack with a specified initial capacity or by copying an existing stack.

Methods in Stack Class

It returns true if nothing is on the top of the stack. Else, returns false.

Returns the element on the top of the stack, but does not remove it.

Removes and returns the top element of the stack. An ‘EmptyStackException’

An exception is thrown if we call pop() when the invoking stack is empty.

Pushes an element on the top of the stack.

It determines whether an object exists in the stack. If the element is found,

It returns the position of the element from the top of the stack. Else, it returns -1.

Methods inherited from class java.util.Vector

Appends all of the elements in the specified Collection to the end of this Vector,

in the order that they are returned by the specified Collection’s Iterator.

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.

Returns the index of the first occurrence of the specified element in this vector, or -1

Читайте также:  Php file put contents utf 8

if this vector does not contain the element.

Returns the index of the last occurrence of the specified element in this vector, or -1

If this vector does not contain the element.

Returns the index of the last occurrence of the specified element in this vector,

searching backward from the index, or returns -1 if the element is not found.

Returns a list iterator over the elements in this list (in proper sequence),

starting at the specified position in the list.

Returns an array containing all of the elements in this Vector in the correct order; the runtime

type of the returned array is that of the specified array.

Prioritize use of Deque over Stack -:

The Stack class in Java is a legacy class and inherits from Vector in Java. It is a thread-safe class and hence involves overhead when we do not need thread safety. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.

Java

One more reason to use Deque over Stack is Deque has the ability to use streams convert to list with keeping LIFO concept applied while Stack does not.

Java

Using Stack - 1 2 Using Deque - 2 1

Example:

In Java, a static class is a nested class that is declared with the static modifier. A static class can only access static members of its outer class, but it can be instantiated without creating an instance of the outer class.

Here’s an example of a static class in Java:

Java

MyStaticClass id: 1 MyStaticClass id: 2

In this example, MyOuterClass contains a static nested class called MyStaticClass. MyStaticClass has an instance field called id, which is initialized to a unique value each time a new instance of MyStaticClass is created. MyStaticClass also has a method called printId() that prints the value of id.

In the main() method of MyOuterClass, we create two instances of MyStaticClass and call the printId() method on each instance. The output shows that each instance has a unique id value.

  • Note that since MyStaticClass is declared as static, we can create instances of it without creating an instance of MyOuterClass. This is different from non-static nested classes, which can only be instantiated using an instance of their outer class.

Static classes are useful when we want to encapsulate functionality that is closely related to a specific class, but does not depend on any specific instance of the class. They can also help to organize code and reduce the clutter of creating new classes for small, related pieces of functionality.

Real time uses of static class in java

In Java, a static class is a class that has only static methods and fields, and cannot be instantiated. Here are some real-time use cases of static classes in Java:

Utility classes: A common use case of static classes in Java is to create utility classes that contain only static methods and are used to perform common operations across the application. For example, the java.util.Collections class is a static class that contains methods for performing various operations on collections such as sorting, searching, and shuffling.

Читайте также:  javascript globals with window

Math functions: Another common use of static classes in Java is for defining math functions that are used across the application. For example, the java.lang.Math class is a static class that provides methods for performing mathematical operations such as trigonometric functions, exponential functions, and logarithmic functions.

Constants: Static classes are also useful for defining constants that are used throughout the application. For example, the java.awt.Color class is a static class that defines various colors as static constants that can be used in the application.

Singleton pattern: The singleton pattern is a design pattern that is used to ensure that only one instance of a class is created in the application. One way to implement the singleton pattern is to use a static class with a private constructor and a static instance variable that returns the single instance of the class.

Helper classes: Static classes are often used as helper classes to provide common functionality that is used across the application. For example, the java.text.NumberFormat class is a static class that provides methods for formatting and parsing numbers.

In summary, static classes in Java are useful for creating utility classes, defining math functions and constants, implementing the singleton pattern, and providing common functionality across the application as helper classes.

Advantages of Static Classes:

Memory Efficiency: Static classes are loaded into memory only once during the lifetime of the application, making them more memory-efficient than non-static classes.
Easy Access: Since static classes are loaded into memory before any object of the class is created, they can be easily accessed without creating an instance of the class.
Utility Classes: Static classes are particularly useful for creating utility classes that don’t need to be instantiated, such as Math class.
Global Accessibility: Static classes can be accessed globally, which means they can be accessed from anywhere in the application.

Disadvantages of Static Classes:

Difficult to Test: Since static classes cannot be instantiated, it can be difficult to test them using automated unit tests.
Tight Coupling: Static classes can lead to tight coupling between classes, which can make the code more difficult to maintain and modify.
Difficulty in Extension: Static classes cannot be extended or subclassed, which can limit the flexibility of the code.
Limited Flexibility: Static classes are limited in their flexibility compared to non-static classes, as they cannot implement interfaces or be used in polymorphic contexts.
It’s important to note that static classes should be used judiciously in Java, and only when their advantages outweigh their disadvantages.

Solve DSA problems on GfG Practice.

Источник

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