题目:
创建购物车实体类,模拟购物车功能(内部使用HashMap,key是商品,value是商品的数量)
需求:
1)添加商品到购物车(输入商品的编号和数量)
2)删除商品(删除购物车中的指定购物项)
3)修改商品(修改商品的数量)
4)显示所购买的商品信息(按购买商品的总价进行升序显示)(可以通过TreeMap的构造方法,传入一个HashMap生成一个TreeMap)
代码:
mport java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class Ex2 {
public static void main(String[] args) {
Product p1 = new Product(1, “苹果”, 5);
Product p2 = new Product(1, “香蕉”, 6);
Product p3 = new Product(1, “雪梨”, 7);
Product p4 = new Product(1, “西瓜”, 8);
ShoppingCart sc = new ShoppingCart();
// 添加商品到购物车
sc.getMap().put(p1, 10);
sc.getMap().put(p2, 20);
sc.getMap().put(p3, 30);
sc.getMap().put(p4, 40);
// 删除购物车中的指定商品
sc.getMap().remove(p2);
// 修改购物车中的商品数量
sc.getMap().put(p1, 100);
// 修改购物车中的商品信息
p1.setPrice(100);
// 显式所有商品
sc.showAllProducts();
}
}
// 购物车
class ShoppingCart {
// private List list;
private HashMap<Product, Integer> map;
public ShoppingCart() {
super();
this.map = new HashMap<Product, Integer>();
}
public HashMap<Product, Integer> getMap() {
return map;
}
public void setMap(HashMap<Product, Integer> map) {
this.map = map;
}
public void showAllProducts() {
// 排序
// Collections.sort(list);
TreeMap<Product, Integer> tm = new TreeMap<Product, Integer>(new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
if (o1.getPrice() * map.get(o1) > o2.getPrice() * map.get(o2)) {
return 1;
} else if (o1.getPrice() * map.get(o1) < o2.getPrice() * map.get(o2)) {
return -1;
} else {
return 0;
}
}
});
tm.putAll(map);
Set<Entry<Product, Integer>> entrySet = tm.entrySet();
for (Entry<Product, Integer> entry : entrySet) {
Product product = entry.getKey();
Integer count = entry.getValue();
System.out.println(product + ",数量:" + count + ",总价:" + product.getPrice() * count);
}
}
}
// 商品
class Product {
private int num;
private String name;
private double price;
// private int count;
public Product(int num, String name, double price) {
super();
this.num = num;
this.name = name;
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [num=" + num + ", name=" + name + ", price=" + price + "]";
}
}