开发者

Duplicate a Java Hashtable

I have a que开发者_高级运维stion about duplicate Hashtables in Java (maybe duplicate Java Collections).

My Hashtable have pairs like this:

  • Key: String
  • Value: Objects of type C

C looks like this:

public interface A extends Cloneable, Serializable{...}

public abstract class B implements A{...}

public class C extends B{...}

I want to copy this hashtable in another variable with the same content by using new Hashtable(Map t). My question is: Which are the conditions for the value objects to make this operation? Can I use the Hashtable copy constructor for this?

I can use SerializationUtils.clone for the values, but it takes too long to execute.

Thanks in advance.


If you don't need a deep copy, then using new Hashtable(Map t) should work just fine.

SerializationUtils.clone() serializes and de-serializes the entire object-graph referenced by the Map, that's why it takes so long. It creates a true deep-copy, however (provided you don't have funny serialization-stuff going on in your classes).


If your C class or one of its interfaces also supplies a public .clone() method (and this really does what you want for single C objects), a simple way without serialization would be this (using HashMap instead of Hashtable, but it does not really matter here):

/**
 * deeply clones a Map by cloning all the values.
 */
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());
    }
}


You can use new Hashtable(Map t), just be aware that the second Hashtable will contain the same instances as the first one (not copies of the objects)...

And by the way you should consider using HashMap rather then Hashtable, Hashtable is an older class that is synchronized where HashMap is the unsynchronized equivalent, the other difference is that HashMap also permits null...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜