Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Hashtable as final in java

Tags:

java

hashtable

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????

like image 401
Sathish Avatar asked Nov 03 '11 14:11

Sathish


People also ask

Can we declare HashMap as final?

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.

Can we modify final Map?

final means that the reference can't be altered, not the object itself. Final does not imply unmodifiable, unless the object is immutable. If you want an unmodifiable map have a look at the Collections class, or alternatively wrap the map in your own custom immutable class.


1 Answers

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.

like image 146
Joe Avatar answered Oct 01 '22 03:10

Joe