Reputation: 17
I'm currently having a problem with the get() method used with hashtables.
My initialization code:
Hashtable<Integer, pageEntry> pageTable = new Hashtable<Integer, pageEntry>();
Hashtable<Integer, LinkedList<Integer>> lookAhead = new Hashtable<Integer, LinkedList<Integer>();
//Initialize pageTable and co.
for(int i = 0; i < 10; i++) {
pageEntry p = new pageEntry();
pageTable.put(i, p);
lookAhead.put(i, new LinkedList<Integer>());
}
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.
Upvotes: 0
Views: 45
Reputation: 567
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.
Upvotes: 0
Reputation: 111339
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.
Upvotes: 2