使用数组实现缓存例子

来源:互联网 发布:中国大数据科学家论坛 编辑:程序博客网 时间:2024/06/07 05:33
public class CacheFinal{private final String name;private static CacheFinal[] cache = new CacheFinal[10];//记录缓存实例在缓存的位置,cache[p-1]是最新的缓存实例private static int p =0;public CacheFinal(String name){//是否隐藏构造器取决于系统需要this.name = name;}public String getName(){return name;}public static CacheFinal valueOf(String name){//遍历已经缓存的对象for(int i =0; i<p;i++){//如果已有相同实例,直接返回该缓存的实例if(cache[i] != null && cache[i].getName().equals(name)){return cache[i];}}//如果缓存已经满了if(p==10){//覆盖第一个对象cache[0] = new CacheFinal(name);//把p设为1p=1;return cache[0];}else{//把新创建的对象缓存起来,p加1cache[p++] = new CacheFinal(name); return cache[p-1];}}//equals方法public boolean equals(Object obj){if(obj instanceof CacheFinal){CacheFinal cf = (CacheFinal) obj;if(name.equals(cf.getName())){return true;}}return false;}//hashcode方法public int hashCode(){return name.hashCode();}public static void main(String[] args){CacheFinal c1 =  CacheFinal.valueOf("hello");CacheFinal c2 =  CacheFinal.valueOf("hello");//比较是否是引用了同一个对象System.out.println(c1 == c2);}}

java.lang.Integer类,就采用了这种缓存处理策略,如果采用new构造器类创建Integer对象,则每次返回全新的Integer对
象,如果采用valueOf方法来创建Integer对象,则会缓存该方法创建的对象。