Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to use Stack.indexOf method in Java

Programming Bytes

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

The indexOf method of the Stack class can be used to get the index of the first occurrence of the specified element in the stack object.

Syntax

public int indexOf(Object obj);

Parameter

  • obj: The element to be searched in the stack is passed as an argument.

Return value

This method returns the first index at which the specified element is present in the stack. If the element is not present in the stack, then -1 is returned.

Code

The code below demonstrates how to use the indexOf method.

import java.util.Stack;
class IndexOfExample {
    public static void main( String args[] ) {
      Stack<String> stack = new Stack<>();
      stack.push("1");
      stack.push("2");
      stack.push("1");
      System.out.println("The stack is " + stack);

      System.out.println("First Index of element '1' is : " + stack.indexOf("1"));
      System.out.println("First Index of element '2' is : " + stack.indexOf("2"));
      System.out.println("First Index of element '3' is : " + stack.indexOf("3"));
    }
}

Explanation

In the code above:

  • In line number 1, we import the Stack class.

  • In line number 4, we create a new object for Stack object with the name stack.

  • From line numbers 5 to 7, we use the push method of the stack object to add three elements ("1","2","3") to the stack.

  • In line number 10, we use the indexOf method of the stack object to get the index of the first occurrence of the element "1". The element "1" is present at two indices: 0 and 2. We get 0 as a result since that is the first occurrence.

  • In line number 11, we use the indexOf method of the stack object to get the index of the first occurrence of the element "2". The element "2" is present only at index 1, so it is returned.

  • In line number 12, we use the indexOf method of the stack object to get the index of the first occurrence of the element "3". The element "3" is not present in the stack, so -1 is returned.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring