public static void main(String[] args) { Items i1=new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Items i2=new Items(2,"李宁运动鞋","温州",300,500,"002.jpg"); Items i3=new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Cart c=new Cart(); c.addGoodsInCart(i1, 1); c.addGoodsInCart(i2, 2); c.addGoodsInCart(i3, 5); Set<Map.Entry<Items, Integer>> items=c.getGoods().entrySet(); for(Map.Entry<Items, Integer> obj:items){ System.out.println(obj); } System.out.println("购物车的总金额:"+c.getTotalPrice()); }
运行结果: 商品编号:1,商品名称:沃特篮球鞋=5 商品编号:2,商品名称:李宁运动鞋=2 购物车的总金额:1600.0
在add的方法里你没有写
if(goods.containsKey(item)){ goods.put(item, goods.get(item)+num); }else{ goods.put(item, num); }
因为Map里的key是不可以重复的,你2次添加的i1和i3相当于重复添加了一个key,后者把前者的value值覆盖了