不,您不能将其用作开关条件。您可以通过将 get 方法扩展到另一个类来覆盖它,或者您可以尝试如下:
Map<String, String> test = new HashMap<String, String>();
test.put("today", "monday");
String s = test.get("hello") == null? "default value" : test.get("hello");
System.out.println("Test =:" + s);
或者
final String defaultValue = "default value";
Map<String, String> test = new HashMap<String, String>() {
@Override
public String get(Object key) {
String value = super.get(key);
if (value == null) {
return defaultValue;
}
return value;
};
};
test.put("today", "monday");
System.out.println("Test =:" + test.get("nokey"));
你也可以通过简单地使用Properties
class 而不是HashMap
.
Properties properties = new Properties();
properties.setProperty("key1", "value of key1");
String property1 = properties.getProperty("key1", "default value");
String property2 = properties.getProperty("key2", "default value");
System.out.println(property1);
System.out.println(property2);
打印:
value of key1
default value