我尝试创建这样的内容作为枚举:
public final class CoCoreMemory<T>{
public static final CoCoreMemory<CoeUser> users = new CoCoreMemory<CoeUser>();
public static final CoCoreMemory<CoeAdmin> admins = new CoCoreMemory<CoeAdmin>();
public static final CoCoreMemory<CoeRequest> requests = new CoCoreMemory<CoeRequest>();
private HashMap<String, T> mem = new HashMap<String, T>();
public int add(String zzf, T t){
int result = -1;
if(!mem.containsKey(zzf)) {
mem.put(zzf, t);
result = 100;
}
return result;
}
private CoCoreMemory(){
}
}
我的尝试如下.....
public enum Memory<T>{
<CoeUser>users, <CoeAdmin> admins, <CoeRequest> requests;
private HashMap<String, T> mem = new HashMap<String, T>();
public int add(String zzf, T t){
int result = -1;
if(!mem.containsKey(zzf)) {
mem.put(zzf, t);
result = 100;
}
return result;
}
}
实际上我只想让一定数量的实例拥有自己的某种类型的HashMap。但是通用的枚举根本不可能,是吗?
任何其他解决方案可以获得这样的东西吗?
答案 0 :(得分:0)
对您的实例使用带有静态常量的普通类型类,如下所示:
public class Memory<T> {
public static final Memory<CoeUser> USERS = new Memory<CoeUser>();
public static final Memory<CoeAdmin> ADMINS = new Memory<CoeAdmin>();
public static final Memory<CoeRequest> REQUESTS = new Memory<CoeRequest>();
private Map<String, T> mem = new HashMap<String, T>();
public int add(String zzf, T t){
int result = -1;
if (!mem.containsKey(zzf)) {
mem.put(zzf, t);
result = 100;
}
return result;
}
}
当您需要使用它们时,只需:
int result = Memory.USERS.add("foo", myCoeUser);
左,第一次使用Memory类时,实例会自动初始化。另外,约定是常量(即static final
)全部大写(如果需要,下划线分隔单词)