javabean思想
public static void main(String args[]) {
//模拟10个不重复的商品加入集合
HashSetdata = new HashSet<>();
Random random = new Random();
for (int i = 0; i < 10; i++) {
int goodsId = random.nextInt(100);
boolean isAdded = data.add(new Product(goodsId, goodsId + "name", goodsId, "util", goodsId));
if (!isAdded) {
i--;
}
}
//如果知道一个id,得到所有信息?
//将这个data转化为map,键为id值为javabean
HashMaphashMap = new HashMap<>();
for (Product item : data) {
hashMap.put(item.goodsId, item);
}
//拿到id,get就行了
hashMap.get(??);
}
class Product {
/**
* 商品编号
*/
int goodsId;
/**
* 商品名称
*/
String name;
/**
* 商品价格
*/
double price;
/**
* 商品单位
*/
String util;
/**
* 商品数量
*/
double num;
public Product(int goodsId, String name, double price, String util, double num) {
this.goodsId = goodsId;
this.name = name;
this.price = price;
this.util = util;
this.num = num;
}
@Override
public boolean equals(Object obj) {
return this.goodsId == ((Product) obj).goodsId;
}
@Override
public String toString() {
return "Product{" +
"goodsId=" + goodsId +
", name='" + name + '\'' +
", price=" + price +
", util='" + util + '\'' +
", num=" + num +
'}';
}
}