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

本文介绍了一种利用数组作为缓存池实现的缓存实例不可变类设计方法,通过覆写equals和hashCode方法确保了缓存的有效性。同时对比了Integer类的缓存机制,展示了不同情况下对象创建和缓存的区别。
/**
 * 缓存实例的不可变类
 * @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
		
	}

}




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值