📄 cart.java
字号:
/* *购物车类 */package com.tarena.entity;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.List;public class Cart { /* * 条目集合 * 帐单总价 * */ private HashMap<Integer,Item> items=null; private double cost=0; /* * 一共8个方法(不包括get,set方法和构造器) * addItem,添加条目 * modifyNumberByProductId,修改一个条目的商品数量 * deleteItemByProductId,根据商品号删除一个条目 * deleteItemsByProductId,根据商品号删除多个条目(调用deleteItemByProductId方法,项目中未使用) * clear,清空购物车 * getCartItem,取得条目集合 * getItemNumber,得到条目数量 * isEmpty,购物车是否为空(未使用) * */ public Cart(){ items=new HashMap<Integer,Item>(); } public HashMap<Integer,Item> getItems() { return items; } public void setItems(HashMap<Integer, Item> items) { this.items = items; } public double getCost() { cost=0; /*如果帐单总金额不在方法里重置为0, 那么页面上的数据会在刷新后发生错误, 因为前一次调用方法后,cost已经不是0了*/ Iterator it=items.values().iterator(); while(it.hasNext()){ Item item=(Item) it.next(); cost=item.getCost()+cost; } return cost; } public void setCost(double cost) { this.cost = cost; } /* * 增加条目 * */ public void addItem(Product product,int number){ if(!items.containsKey(product.getId())){ Item item=new Item(product,number); item.setCost(item.getCost()); items.put(product.getId(),item); } } /* * 修改商品数量 * */ public void modifyNumberByProductId(Integer productId,int number){ Iterator it=items.values().iterator(); while(it.hasNext()){ Item item=(Item) it.next(); if(item.getProduct().getId().equals(productId)){ item.setNumber(number); item.setCost(item.getCost()); } } } /* * 按商品编号删除一个条目 * */ public void deleteItemByProductId(Integer productId){ items.remove(productId); } /* * 按商品编号删除多个条目 * */ public void deleteItemsByProductId(Integer[] productId){ int j=productId.length; for(int i=0;i<j;i++){ deleteItemByProductId(productId[i]); } } /* * 清空购物车 * */ public void clear(){ items.clear(); } public Collection getCartItem(){ return items.values(); } /* * 条目数量 * */ public int getItemNumber(){ return items.size(); } /* * 购物车是否为空 * */ public boolean isEmpty(){ return items.isEmpty(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -