一、缓存中的公共数据平台
一个项目中,有些数据需要被不同的活动调用、修改,应该将这些数据“独立”出来。缓存、数据库、远程服务器,放在哪里?当然,如果数据体量不大,放在缓存中最合适,数据库、服务器更多时候用于备份存储。数组、ArrayList、HashMap,使用哪种结构?
数组需要确定长度,ArrayList不便于搜索。HashMap有“键”和“值”,键用来找位置,值用来存数据,若值是一个类对象或数组的话,就可以存很多数据,而且不用考虑条目之间的存储顺序,不讲“先来后到”,想要谁、想覆盖谁,只要输键即可,这多像缓存中的一张表啊。代码示例如下:
在项目中建一个“存储模型”类如BuyInfoSortMall:
public class BuyInfoSortMall {
private int quantity;
private String name;
public int getQuantity() {return quantity;}
public void setQuantity(int quantity) {this.quantity = quantity; }
public String getName() { return name; }
public void setNamet(String name) {this.name = name;}
}
再创建一个用于存放HashMap的“空中平台”类,如SkyPlatform:
public class SkyPlatform {
// 缓存中保存客户已购产品信息的平台,键是产品id,值是一个类(其中保存产品的其它信息)
public static HashMap<Integer, BuyInfoSortMall> tempInfoSortMall = new HashMap<>();
}
然后在有需求的地方进行存、取等操作,如:
......
count = count + 10;
BuyInfoSortMall b = new BuyInfoSortMall();
b.setQuantity(count);
SkyPlatform.tempInfoSortMall.put(id ,b); // 放入HashMap中
......
二、HashMap使用中的“小坑”
对HashMap中的数据进行“取”操作时,要特别注意HashMap中是否“有”想要的数据,若无想要的数据,却“强行”取出,并对其进行操作,运行时就会出现错误提示,如
......
BuyInfoSortMall bism = SkyPlatform.tempInfoSortMall.get(id);
//获取tempInfoSortMall中对应id对应类中的Quantity(数量)值
int count = bism.getQuantity();
......
此时IDE并不提示错误,即语法上不错。若tempInfoSortMall中不存在id对应的对象,运行时系统会报错:Attempt to invoke virtual method ‘…’ on a null object reference。所以应做“对象是否为空”的判断:
......
BuyInfoSortMall bism = SkyPlatform.tempInfoSortMall.get(id);
int count;
if (bism == null){
count = 0;
} else {
//获取tempInfoSortMall中对应id对应类中的Quantity(数量)值
count = bism.getQuantity();
}
......
输入代码时语法不错,系统也不提示错误,但逻辑有错,“本来里面就没有,取什么取”,所以运行时系统要报错,也算是一个小坑吧。