Java的get()方法将初始化的Hashtable键更改为Null。

huangapple go评论69阅读模式
英文:

Java get() changes initialized Hashtable keys to Null

问题

以下是翻译好的内容:

我目前在使用哈希表的get()方法时遇到了问题。

我的初始化代码:

Hashtable<Integer, pageEntry> pageTable = new Hashtable<Integer, pageEntry>();
Hashtable<Integer, LinkedList<Integer>> lookAhead = new Hashtable<Integer, LinkedList<Integer>>();

// 初始化pageTable和其他内容
for (int i = 0; i < 10; i++) {
    pageEntry p = new pageEntry();
    pageTable.put(i, p);
    lookAhead.put(i, new LinkedList<Integer>());
}

当我使用System.out.println(lookAhead);时,输出如下所示:

{0=[]}
{1=[], 0=[]}
{2=[], 1=[], 0=[]}
{3=[], 2=[], 1=[], 0=[]}
{4=[], 3=[], 2=[], 1=[], 0=[]}

如果我使用System.out.println(lookAhead.get(0)),输出如下所示:

[]
[]
[]
[]
[]

然而,如果我使用System.out.println(lookAhead.get(3)),输出会变成:

null
null
null
[]
[]

我是否忽视了某些原因,导致它将我的值更改为null?

感谢您的时间。

英文:

I'm currently having a problem with the get() method used with hashtables.

My initialization code:

		Hashtable&lt;Integer, pageEntry&gt; pageTable = new Hashtable&lt;Integer, pageEntry&gt;();
		Hashtable&lt;Integer, LinkedList&lt;Integer&gt;&gt; lookAhead = new Hashtable&lt;Integer, LinkedList&lt;Integer&gt;();
		
		//Initialize pageTable and co.
		for(int i = 0; i &lt; 10; i++) {
			pageEntry p = new pageEntry();
			pageTable.put(i, p);
			lookAhead.put(i, new LinkedList&lt;Integer&gt;());
		}

when I use System.out.println(lookAhead);, the output is as follows:

{0=[]}
{1=[], 0=[]}
{2=[], 1=[], 0=[]}
{3=[], 2=[], 1=[], 0=[]}
{4=[], 3=[], 2=[], 1=[], 0=[]}

If I use System.out.println(lookAhead.get(0)), the output is as follows

[]
[]
[]
[]
[]

However, if I use System.out.println(lookAhead.get(3)), the output changes to

null
null
null
[]
[]

Is there some reason I'm overlooking as to why it changes my values to null?

Thanks for your time.

答案1

得分: 2

get 方法在键不存在于映射中时返回 null

在前3次迭代中,键不存在于映射中。在第4次迭代中添加了该键,输出显示从第4次迭代开始与该键关联的值。

英文:

The get method returns null when the key is not present in the map.

In the first 3 iterations, the key is not present in the map. It's added on the 4th iteration, and the output shows a value associated with the key from the 4th iteration onwards.

答案2

得分: 0

这取决于你访问了lookAhead.get(3)的位置。

当你使用lookAhead.get(0)时,程序会打印出空的链表,这些链表在你的哈希表中被初始化为索引'0'。

你会访问索引位置3(lookAhead.get(3)),但根本没有进行初始化。因此,程序会对不存在的键打印出null。

英文:

It depends on where you accessed lookAhead.get(3)

When you use lookAhead.get(0), the program is printing the empty linkedlists which were initialized to the index '0' in your HashTable.

You would have accessed the index location 3 (lookAhead.get(3)) without initializing at all. So, the program is printing null for non existent keys.

huangapple
  • 本文由 发表于 2020年4月6日 04:37:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/61049165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定