Листинг 4.2. Начало кода класса ShoppingCart (ShoppingCart.java)
package com.XmlEcomBook.catalog;
import java.io.*;
import java.util.* ;
public class ShoppingCart implements java.io.Serializable
{ private Vector items ; // maintains order of selection of items
private Hashtable itemsById ;
public ShoppingCart(){
items = new Vector();
itemsById = new Hashtable();
}
// items vector may be empty
public Vector getItems(){ return items ; }
// returns CartItem for this id or null if not in list
public CartItem getProdById(String s ){
return (CartItem) itemsById.get( s );
}
// CartItem is assumed to be unique
public int addItem( CartItem x ){
items.addElement( x );
itemsById.put( x.getId() , x );
return items.size();
}
В листинге 4.3 показаны остальные методы класса ShoppingCart. Поскольку мы храним ссылки на объекты Cartltem в двух коллекциях, для удаления элемента из объекта HashTable применяется метод removeByld с указанием идентификатора товара и затем вызывается метод removeEl eraent вектора items.