【发布时间】:2016-05-04 18:48:05
【问题描述】:
考虑以下代码:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author Colby
*/
public class Entity {
//test code
public static void main(String[] args) {
Entity e = new Entity();
e.put("username", "colby");
e.put("level", 99);
e.put("hours played", Long.MAX_VALUE - 1);
e.put("banned", true);
String username = e.get("username");
int level = e.get("level");
long played = e.get("hours played");
boolean banned = e.get("banned");
System.out.println(username);
System.out.println(level);
System.out.println(played);
System.out.println(banned);
}
public Entity() {
map = new ConcurrentHashMap<>();
}
private final Map<String, Object> map;
public <T> void put(String key, T value) {
map.put(key, value);
}
public <T> T get(String key) {
return (T) map.get(key);
}
public boolean has(String key) {
return get(key) != null;
}
}
一个非常有用的属性系统。现在当我做这样的事情时,我的问题就来了:
int i = e.get("non existent key");
map get 将返回 null,因此会在拆箱时抛出 NPE。
我尝试的解决方案是:
public <T> T get(String key) {
Object o = map.get(key);
if(o == null) {
if(T instanceof Integer) {
return (T) new Integer(-1);
}
}
return (T) o;
}
但是,我得到一个错误,在 instanceof 行上找不到符号 T。我该如何改进这段代码?
【问题讨论】:
-
get不会发生拆箱。出现您的错误是因为instanceof的左侧需要是引用值表达式,而不是类型。使用o instanceof Integer。摆脱== null。instanceof已经针对null进行了验证。 -
如果您尝试将
get的结果分配给原始变量,则会发生拆箱。 -
@Pillar 如果 o == null 则它不会是 instanceof Integer,因此该方法将返回 null 并在“int i = get...”这一行抛出 NPE
-
if (o instanceof Integer)然后返回o。如果不是,则返回一些不是null的默认值,如果您想阻止 NPE。 -
没有很好的方法来做到这一点。尽可能避免它。 codeaffine.com/2015/03/04/…
标签: java generics dictionary return-type autoboxing