Click here to Skip to main content
15,878,871 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all, here's the code i've confusion in. while printing the output of the following code, i can see number 10 also getting printed which is confusing because as per Hashtable(2,3) , we can only put 6 entries inside hash object, isn't it ? Explain me if I am wrong. Please also tell me by saying load factor is 3, and capasity is 2, how will it work internally ? will it create first hashtable with 2 entry capasity and then if third entry comes in, it will create another hashtable with 2 entry capasity or will it continue the existing hashtable by expanding it with 3rd and 4th row ?


import java.util.*;

public class hash {
public static void main (String args[]) throws Exception {

Hashtable hash = new Hashtable(2,3); // --> threshold is 6

for (int i = 0; i <= 10; i++)
{
Integer integer = new Integer ( i );
hash.put( integer, "Number : " + i);
}

System.out.println (hash.get(new Integer(5)));

System.out.println (hash.get(new Integer(10)));

}
Posted
Updated 10-Dec-09 10:56am
v3

A hashtable will grow as new key, value pairs are inserted. What you are specifying in the constructor is an initial capacity and a load factor (which specifies how full the HashTable gets before increasing it's capacity). The load factor should never be higher than 1.0 . You probably don't need to use this constructor at all. You could just use:

Hashtable hash = new Hashtable(); 


I am a little confused as to why
hash.get(new Integer(10)) 
isn't return null.
 
Share this answer
 
@jazzy

" load factor (which specifies how full the HashTable gets before increasing it's capacity)."

An example:

Start with an initial capacity of 10 and a load factor of 0.75 . If you add 10 elements to the HashTable, the first 7 just compute a hash and add the element to a bin. However, on the 8th add operation, the hashtable will increase its capacity. This means the HashTable will create a new larger container ,which is probably an implemented as an array, and copy the contents of the old container into the new container.
 
Share this answer
 
@ rick : thanks for you prompt reply. but can you explain me with a small example what do you mean to say by

" load factor (which specifies how full the HashTable gets before increasing it's capacity)."
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900