Java Reference
In-Depth Information
myStocks.buy(30, 45) indicates a purchase of 30 shares at $45 per share. However, notice that the
implementation of buy adds each of the 30 shares to a queue. Figure 10-9a shows such a queue. The
advantage of this approach is that sell can remove as many or as few shares as necessary.
Suppose that we instead encapsulate the purchase of 30 shares into one object and add it to the queue, as
Figure 10-9b illustrates. If we then sell 20 of those shares, we would remove the object from the queue and
learn the shares' purchase price. But we would have 10 shares that must remain in the queue. Since these are
the oldest shares, we could not simply add them to the back of the queue; they must remain at the front. The
ADT queue has no operation that modifies its front entry, nor does it have one to add an object to its front. If
each entry has set methods, however, Java will allow the client to modify the entry at the front by using the
reference that getFront returns. In this case, you would not remove the front entry until you have sold all of
the shares it represents. Exercise 10 at the end of this chapter asks you to explore this approach.
On the other hand, if each entry in the queue does not have set methods, you would not be able
to modify it. The queue would not be the right ADT to use when each entry represents more than
one share of stock. Segment 10.14 explores another ADT that you can use instead.
FIGURE 10-9
A queue of (a) individual shares of stock; (b) grouped shares
(a)
45
45
45
(b)
30 45
Note: A class that has set methods is a class of mutable objects . A class without set meth-
ods is a class of immutable objects . Chapter 30 talks about such classes in more detail.
Java Class Library: The Interface Queue
10.13
The standard package java.util in the Java Class Library contains an interface Queue that is simi-
lar to our QueueInterface but specifies more methods. We list here a selection of method headers
similar to the ones you have seen in this chapter. We have highlighted where they differ from our
methods. Once again, T is the generic type.
public boolean add(T newEntry)
Adds a new entry to the back of this queue, returning true if successful and throwing an exception if not.
public boolean offer(T newEntry)
Adds a new entry to the back of this queue, returning true or false according to the success of
the operation.
public T remove()
Retrieves and removes the entry at the front of this queue, but throws NoSuchElementException
if the queue is empty prior to the operation.
public T poll()
Retrieves and removes the entry at the front of this queue, but returns null if the queue is empty
prior to the operation.
public T element()
 
 
Search WWH ::




Custom Search