Creating Hashtable as final in java

Because final marks the reference, not the object. You can't make that reference point to a different hash table. But you can do anything to that object, including adding and removing things.

Your example of an int is a primitive type, not a reference. Final means you cannot change the value of the variable. So, with an int you cannot change the value of the variable, e.g. make the value of the int different. With an object reference, you cannot change the value of the reference, i.e. which object it points to.


You can use Collections.unmodifiableMap to get an unmodifiable wrapper over your hash table.

Example:

import java.util.*;
class Test{

    public static final Map<String,Integer> MYHASH;
    static{
        Hashtable<String,Integer> tmp = 
            new Hashtable<String,Integer>();
        tmp.put("A",65);
        tmp.put("C",67);
        MYHASH = Collections.unmodifiableMap(tmp);
    }

    public static void main(String[] args){

        System.out.println(MYHASH.get("A"));

        //this will throw
        //java.lang.UnsupportedOperationException
        MYHASH.put("B",66);    

    }

}

Only the reference is final, its methods can of course be called just as for a non-final reference.

Use Collections.unmodifiableMap(map) to make a map unmodifiable.


Try and wrap your Hashtable with an unmodifiable map using Collections.unmodifiableMap( MYHASH ). This should throw exceptions when you try to change something in the map, i.e. add or remove entries. (Note that MYHASH should then be of type Map<String, String> and not Hashtable<String, String>.)

Regarding the final keyword: as the others already said, it means that you can't assign another Hashtable to MYHASH but the map itself is still mutable. To change this you have to wrap it with some immutable wrapper, like the UnmodifiableMap mentioned above.


As Joe said, this is because final marks the reference not the object.

However, you can do what you want with Collections.unmodifiableMap (see here)