Confused on a shallow copy of a hash table

I came across several articles / explanations on shallow copying and deep copy of hash tables, the more I read, the more confused I am.

Hashtable ht = new Hashtable(); ht.Add("1", "hello"); Hashtable ht2 = new Hashtable(); ht2 = ht; // case1: is this shallow copy? ht2["1"] = "H2"; Hashtable ht3 = new Hashtable(ht); // case2: is this shallow copy? ht3["1"] = "H3"; Hashtable ht4 = new Hashtable(); ht4 = (Hashtable)ht.Clone(); // case3: is this shallow copy? ht4["1"] = "H4"; 
  • Case 1: result, changing the contents of ht becomes the same with ht2.
  • Case2: result, ht content is different from ht3.
  • Case3: result, ht content is different from ht4.

If Case2 and Case3 are shallow copy, should the result not be the same as Case1?

Does this also happen with List, ArrayList, etc.

+4
source share
1 answer

In case 1, both ht2 and ht belong to the same Hashtable instance.

In cases 2 and 3, ht3 and ht4 refer to different objects created by copying the original Hashtable entries.

Please note that even when using a β€œdeep” copy (creating a new mapping), you will still copy links. For example:

 var original = new Dictionary<int, StringBuilder>(); original[10] = new StringBuilder(); var copy = new Dictoinary<int, StringBuilder>(original); copy[20] = new StringBuilder(); // We have two different maps... Assert.IsFalse(original.ContainsKey(20)); // But they both refer to a single StringBuilder in the entry for 10... copy[10].Append("Foo"); Assert.AreEqual("Foo", original[10].ToString()); 
+2
source

All Articles