Java Reference
In-Depth Information
Method
Description
search
(Object anObject)
This will return an int value which is the position on the stack of
the reference to the object passed as an argument. The reference at
the top of the stack is at position 1, the next reference is at position
2, and so on. Note that this is quite different from referencing
elements in a Vector or an array, where indexes are an offset, so
they start at 0. If the object isn't found on the stack, -1 is returned.
empty()
This method returns true if the stack is empty, and false
otherwise.
The only constructor for a Stack object is the default constructor. This will call the default constructor
for the base class, Vector , so you'll always get an initial capacity for 10 objects, but since it's basically a
Vector , it will grow automatically in the same way.
One possible point of confusion is the relationship between the top of a Stack object, and the elements
in the underlying Vector . Intuitively, you might think that the top of the stack is going to correspond
to the first element in the Vector , with index 0. If so you would be totally wrong ! The push() method
for a Stack object is analogous to add() for a Vector , which adds an object to the end of the
Vector . Thus the top of the Stack corresponds to the end of the Vector .
Let's try a Stack object out in an example so we get a feel for how the methods are used.
Try It Out - Dealing Cards
We can use a Stack along with another useful method from the Collections class to simulate
dealing cards from a card deck. Let's start by defining a class to represent a card. Our Card class can
use two integer data members - one to define the suit with values from 0 to 3 for clubs, diamonds,
hearts, and spades, and the other with values from 1 to 13 to specify the face value of the card, 1 being
an ace and 11 through 13 being jack, queen, and king. It will make the code clearer if we define some
constants representing the suits and the court card values. Let's put that as a skeleton class definition:
class Card {
// Suit values
public static final int HEARTS = 0;
public static final int CLUBS = 1;
public static final int DIAMONDS = 2;
public static final int SPADES = 3;
// Card face values
public static final int ACE = 1;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
private int suit;
private int value;
}
Search WWH ::




Custom Search