I came across few articles / explanations on shallow copying and deep copy of hashtables, the more I read, the more I am confused.
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";
- Case1: result, ht content change become same with ht2.
- Case2: result, ht content different with ht3.
- Case3: result, ht content different with ht4.
If Case2 and Case3 are shallow copying, shouldn’t the result be the same as Case1?
Does this happen to List, ArrayList, etc as well?
In case 1, both
ht2andhtrefer to the same instance ofHashtable.In cases 2 and 3,
ht3andht4refer to different objects created by copying the originalHashtableentries.Note that even when taking a “deep” copy (creating a new mapping) you’d still be copying references. So for example: