Java - Data Structures - The Stack Class - Java

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

Apart from the methods inherited from its parent class Vector, Stack defines the following methods −

Sr.No.

Method & Description

1

boolean empty()

Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.

2

Object peek( )

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

3

Object pop( )

Returns the element on the top of the stack, removing it in the process.

4

Object push(Object element)

Pushes the element onto the stack. Element is also returned.

5

int search(Object element)

Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.

Example

The following program illustrates several of the methods supported by this collection −

This will produce the following result −

Output

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Topics