自定义缓存类

package frank;
public class App
{
	public static void main(String[] args)
	{
		CacheTest ct1 = CacheTest.valueOf("1");
		CacheTest ct2 = CacheTest.valueOf("1");
		String s1 = new String("1");
		String s2 = new String("1");
		System.out.println(ct1 == ct2);//true
		System.out.println(s1 == s2);//false
	}
}
class CacheTest
{
	private static final int MAX_SIZE = 20;
	private static CacheTest[] ct = new CacheTest[MAX_SIZE];
	private static int pos = 0;
	private final String name;
	private CacheTest(String name)
	{
		this.name = name;
	}
	public String getName()
	{
		return name;
	}
	public static CacheTest valueOf(String name)
	{
		for(int i = 0;i < MAX_SIZE;i++)
		{
			if(ct[i] != null && ct[i].getName().equals(name))
			{
				return ct[i];
			}
		}
		if(pos == MAX_SIZE)
		{
			ct[0] = new CacheTest(name);
			pos = 1;
		}
		else
		{
			ct[pos++] = new CacheTest(name);
		}
		return ct[pos-1];
	}
	public boolean equals(Object obj)
	{
		if(this == obj)
		{
			return true;
		}
		if(obj!=null && obj.getClass() == CacheTest.class)
		{
			CacheTest ct2 = (CacheTest)obj;
			return name.equals(ct2.getName());
		}
		return false;
	}
	public int hashCode()
	{
		return name.hashCode();
	}
}

  

posted on 2013-08-06 11:43  wp456  阅读(168)  评论(0)    收藏  举报

导航