Cra*_*uin 2 java constants hashmap
假设我想将这些键的潜在键和潜在值存储为常量.我怎样才能做到这一点?或者我应该完全避免它?
这是我自己想到的方法,但正如你将能够看到的那样,它有明显的垮台.
public static class Foo {
public static final String KEY = "foo" ;
public static class Values {
public static final String BAR = "bar" ;
public static final String HEY = "hey" ;
}
}
public static class Another {
public static final String KEY = "another" ;
public static class Values {
public static final String ONE = "1" ;
public static final String TWO = "two" ;
public static final String THREE = "THREE" ;
}
}
Run Code Online (Sandbox Code Playgroud)
这允许我这样访问这些键
miscellaneousMethod( Foo.KEY, Foo.Values.BAR )
miscellaneousMethod( Another.KEY, Another.Values.TWO )
Run Code Online (Sandbox Code Playgroud)
但是,我并不想为每个键/可能值对编写单独的静态内部类.
有没有更好的方法将键值对存储为常量?
我想将它们存储为常量,以便稍后与生成的哈希映射进行比较.所以我可以问这样的东西:
if( map.get( Foo.KEY ).equals( Foo.Values.HEY ) ) { /* do stuff */ }
如果它们都是常量,则可以使用枚举:
public enum ValueEnum {
FOO("foo", "bar", "hey"),
ANOTHER("another", "1", "two", "THREE"),
;
private final String key;
private final Set<String> values;
private ValueEnum(String key, String... values) {
this.key = key;
this.values = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(values)));
}
public final boolean isInMap(Map<String,String> map) {
if(map.containsKey(key)) {
return values.contains(map.get(key));
}
else {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后
if( ValueEnum.FOO.isInMap(map) ) { /* do stuff */ }
Run Code Online (Sandbox Code Playgroud)