Java – how to prevent HashMap or treemap from replacing previous values

If it already exists, how can I prevent HashMap or treemap from replacing the previous key value? In addition, I want to throw an exception to notify the user

Solution

To be honest, any such map will violate the normal map interface However, if you are willing to do so, you can easily create your own map implementation, which is delegated to another map, but only after checking the existence of existing elements:

public final class NonReplacementMap<K,V> implements Map<K,V> {
    private final Map<K,V> original;

    public NonReplacementMap(Map<K,V> original) {
        this.original = original;
    }

    @Override
    public void put(K key,V value) {
        if (original.containsKey(key)) {
            // Or whatever unchecked exception you want
            throw new IllegalStateException("Key already in map");
        }
        original.put(key,value);
    }

    // etc
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>