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): import java.util.Hashtable; public class Q3 { public static void main(String[] args) { Hashtable<String, Integer> tableSrc = new Hashtable<String, Integer>(); Hashtable<String, Integer> tableDest = new Hashtable<String, Integer>(); tableSrc.put("One", 1); tableSrc.put("Two", 2); tableSrc.put("Three", 3); tableSrc.put("Four", 4); tableSrc.put("Five", 5); tableSrc.put("Six", 6); tableSrc.put("Seven", 7); tableSrc.put("Eight", 8); tableSrc.put("Nine", 9); tableSrc.put("Ten", 10); } } Can anybody show me a way I can transfer the contents from tableSrc to tableDest?
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.
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).