简体   繁体   中英

Java get() changes initialized Hashtable keys to Null

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM