Java Reference
In-Depth Information
Stack = 10,20
After push(40), Stack = 10,20,40
After 2 pops, Stack = 10
stack.peek() = 10
stack.isEmpty() = false
After another pop(), stack.isEmpty() = true
Searching an Array
Two methods,
indexOf()
and
lastIndexOf()
, let you search an array for a specified
element. Their signatures are:
indexOf(searchElement, fromIndex)
•
lastIndexOf(searchElement, fromIndex)
The
indexOf()
method searches for the specified
searchElement
in the array
starting at
fromIndex
. If
fromIndex
is not specified, 0 is assumed, meaning that the entire
array is searched. The method returns the index of the first element in the array that is
equal to the
searchElement
using the
===
operator. If the
searchElement
is not found, -1
is returned.
The
lastIndexOf()
method works the same as the
indexOf()
method, except that it
performs the search from the end to the beginning. That is, it returns the index of the last
found element in the array that is equal to the
searchElement
. The following code shows
how to use these methods:
•
var ids = [10, 20, 30, 20];
print("ids = " + ids);
print("ids.indexOf(20) = " + ids.indexOf(20));
print("ids.indexOf(20, 2) = " + ids.indexOf(20, 2));
print("ids.lastIndexOf(20) = " + ids.lastIndexOf(20));
print("ids.indexOf(25) = " + ids.lastIndexOf(25));
ids = 10,20,30,20
ids.indexOf(20) = 1
ids.indexOf(20, 2) = 3
ids.lastIndexOf(20) = 3
ids.indexOf(25) = -1
Search WWH ::
Custom Search