Java Reference
In-Depth Information
It then adds that instance to the front of the deque, since it is these shares that would be sold next.
public double sell( int sharesSold, double pricePerShare)
{
double saleAmount = sharesSold * pricePerShare;
double totalCost = 0;
while (sharesSold > 0)
{
StockPurchase transaction = ledger.removeFront();
double shareCost = transaction.getCostPerShare();
int numberOfShares = transaction.getNumberOfShares();
if (numberOfShares > sharesSold)
{
totalCost = totalCost + sharesSold * shareCost;
int numberToPutBack = numberOfShares - sharesSold;
StockPurchase leftOver = new StockPurchase(numberToPutBack, shareCost);
ledger.addToFront(leftOver); // return leftover shares
// Note: loop will exit since sharesSold will be <= 0 later
}
else
totalCost = totalCost + numberOfShares * shareCost;
sharesSold = sharesSold - numberOfShares;
} // end while
return saleAmount - totalCost; // gain or loss
} // end sell
Java Class Library: The Interface Deque
10.17
The standard package java.util in the Java Class Library contains an interface Deque that is simi-
lar to our DequeInterface but specifies more methods. Here is a selection of the method headers
that this interface declares. The methods that either add, remove, or retrieve entries occur in pairs.
One method in a pair throws an exception if the operation is unsuccessful, while the other method
returns either null or false. T is the generic type of the entries in a deque.
public void addFirst(T newEntry)
Adds a new entry to the front of this deque, but throws one of several exceptions if it cannot.
public boolean offerFirst(T newEntry)
Adds a new entry to the front of this deque, returning true or false according to the success
of the operation.
public void addLast(T newEntry)
Adds a new entry to the back of this deque, but throws one of several exceptions if it cannot.
public boolean offerLast(T newEntry)
Adds a new entry to the back of this deque, returning true or false according to the success
of the operation.
public T removeFirst()
Retrieves and removes the entry at the front of this deque, but throws NoSuchElementException
if the deque is empty prior to the operation.
public T pollFirst()
Retrieves and removes the entry at the front of this deque, but returns null if the deque is
empty prior to the operation.
 
 
Search WWH ::




Custom Search