Shoppingcart class
Bytes -----------------------------------------------------------------------------------------------------------
Import java. util .*;
Public class shoppingcart {
Hashmap items = NULL;
Int numberofitems = 0;
Public shoppingcart (){
Items = new hashmap ();
}
Public synchronized void add (string mid, merchandise m ){
If (items. containskey (MID )){
Shoppingcartitem scitem = (shoppingcartitem) items. Get (MID );
Scitem. incrementquantity ();
} Else {
Shoppingcartitem newitem = new shoppingcartitem (m );
Items. Put (MID, newitem );
}
Numberofitems ++;
}
Public synchronized void remove (string bookid ){
If (items. containskey (bookid )){
Shoppingcartitem scitem = (shoppingcartitem) items. Get (bookid );
Scitem. decrementquantity ();
If (scitem. getquantity () <= 0)
Items. Remove (bookid );
Numberofitems --;
}
}
Public synchronized collection getitems (){
Return items. Values ();
}
Protected void finalize () throws throwable {
Items. Clear ();
}
Public synchronized int getnumberofitems (){
Return numberofitems;
}
Public synchronized double gettotal (){
Double amount = 0.0;
For (iterator I = getitems (). iterator (); I. hasnext ();){
Shoppingcartitem item = (shoppingcartitem) I. Next ();
Merchandise merch = (merchandise) item. getitem ();
Amount + = item. getquantity () * merch. getprice ();
}
Return roundoff (amount );
}
Private double roundoff (Double X ){
Long val = math. Round (x * 100); // cents
Returns Val/100.0;
}
Public synchronized void clear (){
Items. Clear ();
Numberofitems = 0;
}
}
Bytes --------------------------------------------------------------------------------------------------------
Shoppingcartitem class
Bytes --------------------------------------------------------------------------------------------------------
Public class shoppingcartitem {
Object item;
Int quantity;
Public shoppingcartitem (Object anitem ){
Item = anitem;
Quantity = 1;
}
Public void incrementquantity (){
Quantity ++;
}
Public void decrementquantity (){
Quantity --;
}
Public object getitem (){
Return item;
}
Public int getquantity (){
Return quantity;
}
}