I need to know how to for loop through a Hashtable, check for cloneability on each value, and clone if possible. This Hashtable has all String keys, but the values can be of any class. I have come across the following Hashmap example on another Stack Overflow page, but I need to do this with a Hashtable. More specifically, one without brackets. (Hashtable instead of Hashtable<Type, Type>.) I have also seen examples for looping through an ArrayList and cloning each element, but I need to do this with a hashtable. I have posted two pieces of code below: the first is the HashMap example I found and the second is my current proposal and the issues I'm running into.
The HashMap
public Map<String,C> deepCopy(Map<String, C> original) { Map<String, C> copy = new HashMap<String, C>(original.size()); for(Map.Entry<String, C> entry : original.entries()) { copy.put(entry.getKey(), entry.getValue().clone()); } } My proposal
public class _HashtableCloningTest { public Hashtable deepClone(Hashtable original) { Hashtable newH = new Hashtable(original.size()) Set<String> keys = original.keySet(); for (String key : keys) if (original.get(key) instanceof Cloneable) newH.put(key, original.get(key).clone()); return newH; } } This code won't compile. The error says the clone method is on the object class, and the method on that class is protected. I need it to clone on the class of the current value, but since I as the programmer don't know that class, I don't know how to cast it to the proper class.
Any insight and help around this hurdle is greatly appreciated.
Cloneableis basically a disaster in Java. Why does your client know enough about Java to care aboutCloneable, but not enough to know how terribleCloneableis?