Java Reference
In-Depth Information
program without knowing the details of the implementation. That is, we do not need to know
how
the programmer implemented the bag to be able to use it. We only need to know
what
the ADT bag
does. This section assumes that we have a Java class,
Bag
, that implements the Java interface
BagInterface
given in Listing 1-1. The simple examples demonstrate how we can use
Bag
.
Notice that once we choose the data type of the objects to be in a bag, that data type is
enclosed in brackets that follow the interface name and the class name. All entries in the bag then
must have either that data type or a subtype of that data type. The compiler will enforce this
restriction for us. For primitive types, you can place instances of an appropriate wrapper class
into a bag. For example, instead of instances of the primitive type
int
, you could use instances of
the wrapper class
Integer
.
VideoNote
Designing a test for an ADT
1.16
Example: Shopping online.
When you shop online, your selections are saved in a shopping cart,
or bag, until you are ready to check out. The program that implements the shopping website can use
the class
Bag
to maintain the shopping cart. After all, the order in which you choose items to pur-
chase is not important. Listing 1-2 shows a simple example of such a program.
LISTING 1-2
A program that maintains a bag for online shopping
/**
A class that maintains a shopping cart for an online store.
@author Frank M. Carrano
*/
public class
OnlineShopper
{
public static void
main(String[] args)
{
Item[] items = {
new
Item("Bird feeder", 2050),
new
Item("Squirrel guard", 1547),
new
Item("Bird bath", 4499),
new
Item("Sunflower seeds", 1295)};
BagInterface<Item> shoppingCart =
new
Bag<Item>();
int
totalCost = 0;
// statements that add selected items to the shopping cart:
for
(
int
index = 0; index < items.length; index++)
{
Item nextItem = items[index];
// simulate getting item from
// shopper
shoppingCart.add(nextItem);
totalCost = totalCost + nextItem.getPrice();
}
// end for
// simulate checkout
while
(!shoppingCart.isEmpty())
System.out.println(shoppingCart.remove());
System.out.println("Total cost: " +
"\t$" + totalCost / 100 + "." +
totalCost % 100);