When the java type is forced to be converted to generic type V, no error is reported?
欧阳克
欧阳克 2017-06-12 09:23:55
0
2
888
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: No error is reported when running.

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(2)
大家讲道理

Type erasure is Object, and no error will be reported when forced conversion to Object.

phpcn_u1582

There will only be warnings during compilation and no errors will be reported. There are actually such forced transfers everywhere in the Java Collections Framework.
But an error will be reported when running, if V is not Ambiguity or its parent class.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template