In Java, indexOf(o)finds the first element equal to o and returns its index, counting from the bottom of the stack at 0. If nothing matches, it returns -1.
Because it scans upward from the bottom, it finds the oldest copy of a repeated element. Vector adds an overload indexOf(o, fromIndex) that starts the scan at a given index, useful when you need every position. Stack's own search() measures from the top instead.
An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.
Syntax
Pass the value to find, and optionally the index where the upward scan starts.
Java
Stack<String> stack = new Stack<>();
stack.push("red");
stack.push("green");
stack.push("blue");
stack.push("green"); // [red, green, blue, green]
int a = stack.indexOf("green"); // 1 (first match from the bottom)
int b = stack.indexOf("green", 2); // 3 (scan starts at index 2)
int c = stack.indexOf("pink"); // -1
Call
What it does
stack.indexOf(o)
Index of the first match from the bottom, or -1.
stack.indexOf(o, from)
The same scan starting at index from.
stack.indexOf(o) >= 0
The same test as contains(o).
stack.search(o)
A 1-based distance from the top instead.
indexOf checks elements one by one, so its running time grows with the size of the stack.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public int indexOf(Object o)
public synchronized int indexOf(Object o, int index)
Parameters
Parameter
Description
o (Object)
The value to find, compared with equals(); null finds a null element.
index (int)
Only in the two-argument form: where the upward scan starts.
Return Value
Return Value
Description
int
The 0-based index of the first match at or above the start index, or -1.
Type matters. The Integer 7 and the String "7" are not equal, so indexOf(7) finds index 1 and indexOf("7") finds index 0.
null can be found.indexOf(null) compares with == for this special case and returns 2.
equals, not identity. The element at index 3 was created with new String, yet the literal "seven" matches it because String.equals compares characters.
Frequently Asked Questions
The 0-based index of the first element equal to the argument, counted from the bottom, or -1 if there is none.
From the bottom. Index 0 is the first element pushed. Use search() for a distance from the top.
With equals(), so two different String objects with the same text match. A null argument matches a null element.
Call indexOf(o) and then repeatedly indexOf(o, previous + 1) until it returns -1.
indexOf() returns the match closest to the bottom; lastIndexOf() returns the match closest to the top.