Shubham
Shubham

Reputation: 820

Is it possible to make some specific keys of a HashMap read-only?

I have 5 Keys which must not be removed/updated. I provide my own methods to add, get and remove keys of this HashMap.

UnmodifiableMap will make ALL the keys read-only, so I can't use that either. I could maintain a List of these read-only keys and whenever add/remove method is called, I can refer this List and prevent the operation. But is there any other better way to achieve this ?

Thanks in advance!

EDIT: I know I can extend HashMap and override the put method. That's similar to what I said in the problem description above (Maintain a List of read-only keys and prevent operations on them). I thought there could be a way to merge an UnmodifiableMap in a HashMap such that the keys from UnmodifiableMap will remain read-only in the new HashMap and the other keys will have all operations supported on them.

Upvotes: 3

Views: 429

Answers (2)

WilQu
WilQu

Reputation: 7393

Create a Map that will encapsulate two other maps. One of these map will be an unmodifiable map and will contain your read-only keys, the other will be a regular HashMap.

When you get a key, look in both maps, beginning by the unmodifiable map. When you put, use only the second map, after checking that the key is not already in the first map.

Upvotes: 0

Mena
Mena

Reputation: 48434

As Andre mentions, you can inherit from HashMap or other Map implementations.

Here's an anonymous class quick example, self-contained in a main method:

public static void main(String[] args) {
    Map<String, String> myMap = new HashMap<String, String>() {

        private static final long serialVersionUID = 6585814488311720276L;
        @Override
        public String put(String key, String value) {
            if (key != null && !key.equalsIgnoreCase("foo")) {
                return super.put(key, value);
            }
            else {
                throw new IllegalArgumentException("No foo's allowed!");
            }
        }
        // TODO!
        @Override
        public void putAll(Map<? extends String, ? extends String> m) {
            // TODO Auto-generated method stub
            super.putAll(m);
        }
    };
    System.out.println(myMap.put("blah", "blah"));
    System.out.println(myMap.put("foo", "blah"));
}

Output

null
Exception in thread "main" java.lang.IllegalArgumentException: No foo's allowed!
    at test.Main$1.put(Main.java:18)
    at test.Main$1.put(Main.java:1)
    at test.Main.main(Main.java:29)

Upvotes: 6

Related Questions