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)));
}
解决方案
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.
@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.
@ 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)."