Creating Hashtable as final in java

Sathish picture Sathish · Nov 3, 2011 · Viewed 40.3k times · Source

As we know the purpose of "final" keyword in java. While declaring a variable as final, we have to initialize the variable. like "final int a=10;" We can not change the value of "a". But if we go for HashTable its possible to add some value even declaring the HashTable as final.

Example::

 private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() 
{{     put("foo",      1);     
       put("bar",      256);     
       put("data",     3);     
       put("moredata", 27);     
       put("hello",    32);     
       put("world",    65536);  }}; 

Now I am declaring the MYHASH HashTable as final. If I try to add some more elements to this, its accepting.

MYHASH.put("NEW DATA",      256);

Now the "NEW DATA" is added to the HashTable. My questions is Why its allowing to add even its declaring as final????

Answer

Joe picture Joe · Nov 3, 2011

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.