您的位置:首页 > 编程语言 > Java开发

52 Java final 缓存实例的不可变类

2014-02-09 12:06 253 查看
/**
* 缓存实例的不可变类
* @author Administrator
*
*/
/*
* 本列使用一个数组来作为缓存池,从而实现一个缓存实例的不可变类
*/
public class CacheImmutable {

private static int MAX_SIZE=10;
//使用数组来缓存已有的实例
private static CacheImmutable[] cache=new CacheImmutable[MAX_SIZE];
//记录缓存实例在缓存中位置 cache[pos-1] 是最新缓存的实例
private static int pos=0;
private final String name;
private CacheImmutable(String name)
{
this.name=name;
}

public String getName() {
return name;
}

public static CacheImmutable valueOf(String name)
{
//遍历已缓存的对象
for(int i=0;i<MAX_SIZE;i++)
{
//如果已有相同实例,则直接返回该缓存的实例
if(cache[i] !=null &&cache[i].getName().equals(name))
{
return cache[i];
}
}
//如果缓存池已满
if(pos==MAX_SIZE)
{
//把缓存的第一个对象覆盖,即使把刚刚生成的对象放在缓存池的最开始位置
cache[0]=new CacheImmutable(name);
//把pos 设为1
pos=1;
}
else{
//把新创建的独享缓存起来。pos加1
cache[pos++]=new CacheImmutable(name);
}
return cache[pos-1];
}

public boolean equals(Object obj)
{
if(this==obj)
{
return true;
}
if(obj != null && obj.getClass()==CacheImmutable.class)
{
CacheImmutable ci=(CacheImmutable) obj;
return name.equals(ci.getName());
}

return false;
}

public int hashCode()
{
return  name.hashCode();
}

}


public class CacheImmutableTest {

public static void main(String[] args) {
// TODO Auto-generated method stub

CacheImmutable c1=CacheImmutable.valueOf("hello");
CacheImmutable c2=CacheImmutable.valueOf("hello");
System.out.println(c1==c2);//输出 true
}

}


Integer 类缓存

/*
* java.lang.Integer 类,它就采用鱼CacheImmutable了相同的处理策略
* 如采用new 构造器来创建Integer对象,则每次返回全新的Ineger对象;
* 如采用valueOf方法来创建对象,则会缓存该方法创建的对象
*/
//下面示范了Integer 类构造起哦和valueOf方法存在的差异
public class IntegerCacheTest {

public static void main(String[] args) {

//生成新的Integer对象
Integer in1=new Integer(6);
//生成新的Integer对象,并缓存该对象
Integer in2=Integer.valueOf(6);
//直接从缓存中取出Integer 对象
Integer in3=Integer.valueOf(6);
//输出false
System.out.println(in1==in2);
System.out.println(in2==in3);//true

//由于Integer 至缓存-128 到127 之间的值
//因此200 对应的Integer 对象没有被缓存
Integer in4=Integer.valueOf(200);
Integer in5=Integer.valueOf(200);
System.out.println(in4==in5);//false

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: