我需要在Java中创建一个具有Map类型字段的枚举。如何初始化地图字段?有没有办法不创建匿名对象或使用Guava(或类似)库?
public enum Day {
Sunday(new HashMap<>()); // TODO initialize the map
private Map<String, String> map;
Day(Map<String, String> paramMap) {
this.map.putAll(paramMap);
}
public getMap() {return map;}
}
答案 0 :(得分:1)
由于地图的键和值均为String
,因此您可以让构造函数采用变量并让它为您构建地图:
public enum Day {
SUNDAY("Foo", "Fooz",
"Bar", "Barz",
"Hello", "Hi");
private final Map<String, String> map;
Day(String... keysAndValues) {
if ((keysAndValues.length & 1) != 0)
throw new IllegalArgumentException("keysAndValues has odd size: " + Arrays.toString(keysAndValues));
this.map = new HashMap<>();
for (int i = 0; i < keysAndValues.length; i += 2) {
if (keysAndValues[i] == null || keysAndValues[i + 1] == null)
throw new NullPointerException();
if (this.map.put(keysAndValues[i], keysAndValues[i + 1]) != null)
throw new IllegalArgumentException("keysAndValues has duplicate key named '" + keysAndValues[i] + "': " + Arrays.toString(keysAndValues));
}
}
public Map<String, String> getMap() {
return this.map;
}
}
如果您打印SUNDAY
的地图,例如System.out.println(Day.SUNDAY.getMap())
,你得到:
{Bar=Barz, Hello=Hi, Foo=Fooz}
答案 1 :(得分:0)
这是可以通过jdk8并使用功能接口完成的方式
import java.util.Map;
public interface MapProducer<K,V> {
Map<K,V> getMap();
}
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public enum EnumWithMap {
//empty map
TEST1(HashMap::new),
//default map
TEST2(EnumWithMap::getDefMap),
//enum instance map
TEST3(()->{
Map<String,String> map = new HashMap<>();
map.put("key1","val1");
return map;
})
;
private final Map<String,String> map;
EnumWithMap(MapProducer<String,String> mapProducer) {
this.map = Collections.unmodifiableMap(mapProducer.getMap());
}
private static Map<String,String> getDefMap(){
Map<String,String> map = new HashMap<>();
map.put("keyDef","valDef");
return Collections.unmodifiableMap(map);
}
public Map<String, String> getMap() {
return map;
}
}
$ foreach循环的结果:
for(EnumWithMap en:EnumWithMap.values())System.out.println(en.getMap());
将是:
{}
{keyDef=valDef}
{key1=val1}