A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© che201311 中级黑马   /  2013-11-22 23:29  /  1326 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面代码看不懂内存是怎么执行的,理解不了代码的执行过程.
求大神们把内存执行过程详细的说一下.(valueOf方法)这部分最好每一步过程都说一下。
class CacheImmutale
{
private static int MAX_SIZE = 10;
//使用数组来缓存已有的实例
private static CacheImmutale[] cache
= new CacheImmutale[MAX_SIZE];
//记录缓存实例在缓存中的位置,cache[pos-1]是最新缓存的实例
private static int pos = 0;
private final String name;
private CacheImmutale(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public static CacheImmutale 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 CacheImmutale(name);
//把pos设为1
pos = 1;
}
else
{
//把新创建的对象缓存起来,pos加1
cache[pos++] = new CacheImmutale(name);
}
return cache[pos - 1];

}
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if (obj != null && obj.getClass() == CacheImmutale.class)
{
CacheImmutale ci = (CacheImmutale)obj;
return name.equals(ci.getName());
}
return false;
}
public int hashCode()
{
return name.hashCode();
}
}
public class Codes15
{
public static void main(String[] args)
{
CacheImmutale c1 = CacheImmutale.valueOf("hello");
CacheImmutale c2 = CacheImmutale.valueOf("hello");
//下面代码将输出true
System.out.println(c1 == c2);
}
}

评分

参与人数 1技术分 +1 黑马币 +3 收起 理由
FFF + 1 + 3 淡定

查看全部评分

2 个回复

倒序浏览
FFF 金牌黑马 2013-11-23 00:11:56
沙发
本帖最后由 FFF 于 2013-11-23 00:14 编辑

下次发疑问的时候,把代码放代码框里哦、如果不知道代码框在那里。
请看下面这个帖子。
http://bbs.itheima.com/thread-100573-1-1.html
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马