WSN的床垫# Joke - 肚皮舞运动
J*e
1 楼
Write a special singleton class, the class has one integer field,
make sure only one instance of this class will be instantiated for
the same value of the integer field.
以下是我写的, 但是有个问题,这样instance不是static, getInstance()因为用到
instance也不能是static,可以吗?这样解对吗?另外,当singleton object destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()?
import java.util.HashMap;
public class SingletonInteger {
private Integer value;
private SingletonInteger instance;
private static HashMap values;
private SingletonInteger(Integer val)
{
value=val;
}
public synchronized SingletonInteger getInstance(Integer v)
{
if(values==null)
{
values = new HashMap();
}
if(values.containsKey(v)==false)
{
instance = new SingletonInteger(v);
values.put(v,instance);
}
return values.get(v);
}
}
make sure only one instance of this class will be instantiated for
the same value of the integer field.
以下是我写的, 但是有个问题,这样instance不是static, getInstance()因为用到
instance也不能是static,可以吗?这样解对吗?另外,当singleton object destruct的时候,应该把 value从hashmap里删除。怎么实现这个呢?用finalize()?
import java.util.HashMap;
public class SingletonInteger {
private Integer value;
private SingletonInteger instance;
private static HashMap
private SingletonInteger(Integer val)
{
value=val;
}
public synchronized SingletonInteger getInstance(Integer v)
{
if(values==null)
{
values = new HashMap
}
if(values.containsKey(v)==false)
{
instance = new SingletonInteger(v);
values.put(v,instance);
}
return values.get(v);
}
}