When you assign one set to another, a new set is not created, but a new link is created that points to an existing set. So, any change you make in a set with a will be reflected in b .
This is true for any Mutable Object.
But not for Immutable objects.
For example, consider the case for String : -
String s = "a"; String s1 = s; // Both `s` and `s1` points to `"a"` s1 = "b"; // Only s1 will point to "b". `s` still points to "a".
In the above case, the change does not affect the whole link, because Strings immutable. Therefore, any change you make to String will create a new object .
But if you have a mutable object .: -
Set<String> set = new HashSet<String>(); Set<String> set3 = new HashSet<String>(); // A different set object Set<String> set2 = set; // Point to the same set object as "set" set2.clear(); // Will clear the actual object. Pointed by "set" // And thus both the reference pointing to that object, will see the change. set3 = set; // Change reference `set3` to point to the `Set object` pointed by `set` set3.add("a"); // Will change `set` also.
If you want to create a copy of your kit. Do it like this: -
Set<String> set1 = new HashSet<String>(); Set<String> set3 = new HashSet<String>(set1);
source share