在Java中创建Hashtable作为final [英] Creating Hashtable as final in java

查看:85
本文介绍了在Java中创建Hashtable作为final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道java中final关键字的用途。在将变量声明为final时,我们必须初始化变量。比如 final int a = 10;
我们无法更改a的值。但是如果我们选择HashTable就可以添加一些值,甚至可以将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.

示例::

 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);  }}; 

现在我宣布MYHASH HashTable为最终版。如果我尝试为此添加更多元素,则接受它。

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);

现在,NEW DATA被添加到HashTable中。
我的问题是为什么它允许添加甚至其声明为最终????

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

推荐答案

因为最终标志着参考,而不是对象。您不能将该引用指向另一个哈希表。但你可以对这个对象做任何事情,包括添加和删除东西。

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.

你的 int 的例子是原始类型,不是参考。最终意味着您无法更改变量的值。因此,使用 int ,您无法更改变量的值,例如使 int 的值不同。使用对象引用时,不能更改引用的值,即它指向的对象。

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.

这篇关于在Java中创建Hashtable作为final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆