don't click here

Java Question Regarding Hashtables

Discussion in 'Technical Discussion' started by saxman, May 11, 2012.

  1. saxman

    saxman

    Oldbie Tech Member
    I'm doing a training program with a company, and one of the projects involves creating a Hashtable with numbers from 1-10 in it. I have to transfer those numbers into another Hashtable. I've been working with it for the last hour and can't figure it out. Here's what I have so far...

    Code (Text):
    1.  
    2. import java.util.Hashtable;
    3.  
    4. public class Q3 {
    5.    
    6.     public static void main(String[] args)
    7.     {
    8.         Hashtable<String, Integer> tableSrc = new Hashtable<String, Integer>();
    9.         Hashtable<String, Integer> tableDest = new Hashtable<String, Integer>();
    10.        
    11.         tableSrc.put("One", 1);
    12.         tableSrc.put("Two", 2);
    13.         tableSrc.put("Three", 3);
    14.         tableSrc.put("Four", 4);
    15.         tableSrc.put("Five", 5);
    16.         tableSrc.put("Six", 6);
    17.         tableSrc.put("Seven", 7);
    18.         tableSrc.put("Eight", 8);
    19.         tableSrc.put("Nine", 9);
    20.         tableSrc.put("Ten", 10);
    21.     }
    22.  
    23. }
    24.  
    Can anybody show me a way I can transfer the contents from tableSrc to tableDest?
     
  2. Conan Kudo

    Conan Kudo

    「真実はいつも一つ!」工藤新一 Member
    478
    1
    18
    According to the Java spec, you can do shallow copies with clone(), but that means that the destination hash table really only has pointers/references to the source hash table. The only way to duplicate a hash table in Java is to iterate through the source hash table and copy them one by one into the destination hash table.

    Most hash table implementations are like this. Even C++11 hash tables are like this.
     
  3. Glitch

    Glitch

    Tech Member
    175
    12
    18
    Hashtable also has a copy ctor that's subtly different from clone(): clone performs a copy of the backing entry table, thus does not need to recompute the hash, whereas the copy ctor essentially does what Conan Kudo suggests and iterates the Hashtable calling put(key,value) for each entry. Either way is acceptable since both String and Integer are immutable.

    Something worth noting: Hashtable is internally synchronized so if you're only accessing it from one thread you'll get better performance out of a HashMap. Even if you are dealing with a multithreaded application you might want to consider ConcurrentHashMap (Hashtable is legacy code).