"
public class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -3455861209780003757L;
private String name;
public StrictMap(int initialCapacity, float loadFactor, String name) {
super(initialCapacity, loadFactor);
this.name = name;
}
public StrictMap(int initialCapacity, String name) {
super(initialCapacity);
this.name = name;
}
public StrictMap(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public V put(String key, V value) {
if (containsKey(key)) {
throw new RuntimeException("已经存在的key, keyName = " + key);
}
if (key.contains(".")) {
final String shortName = getShortName(key);
if (containsKey(shortName)) {
// question 这边有个问题, 为什么没有抛出ClassCastException。
V ambiguity = (V) new Ambiguity("存在的shortName");
super.put(shortName, ambiguity);
} else {
super.put(shortName, value);
}
}
return super.put(key, value);
}
@Override
public V get(Object key) {
V value = super.get(key);
if (value == null) {
throw new RuntimeException("keyName = " + key + ", 没有获取到value.");
}
if (value instanceof Ambiguity) {
throw new RuntimeException("重复的shortName");
}
return value;
}
static class Ambiguity {
private String name;
public Ambiguity(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
ps:运行时也没报错。
" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/5b9f3dc404e8481dbbd1d88c116843b2.png)
类型擦除为Object,强转为Object不会报错。
######编译时只会有警告,不会报错的。Java Collections Framework里其实到处是这样的强转。
但运行时却会报错,如果V不是Ambiguity或者它的父类的话。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。