package ming;
public class CacheImmutale {
private static int MAX_SIZE = 10;
private static CacheImmutale[] cache = new CacheImmutale[MAX_SIZE];
private static int pos = 0;
private final String name;
private CacheImmutale(String name) {
this.name = name;
}
public String getName() {
return this.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;
} else {
//把新的对象缓存起来
cache[pos++] = new CacheImmutale(name);
}
return cache[pos - 1];
}
@Override
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 static void main(String[] args) {
// TODO Auto-generated method stub
CacheImmutale c1 = CacheImmutale.valueof("hello");
CacheImmutale c2 = CacheImmutale.valueof("hello");
System.out.println(c1==c2);
}
}
转载于:https://www.cnblogs.com/MarchThree/p/3720478.html