Assigning one set to another, and when Clear is executed. Both sets are cleared

1. Initially, two sets are created. 2. Added items to one set. 3. Assigned one set to another. 4. If cleaning is called on one set, both sets are cleared.

Can someone help in solving the problem?

import java.util.HashSet; import java.util.Set; public class SetOperation { Set<Integer> a = new HashSet<Integer>(); Set<Integer> b = new HashSet<Integer>(); void assignAndClear(){ a.add(3); a.add(7); a.add(5); a.add(19); a.add(99); System.out.println("a:" +a ); System.out.println("b:" +b ); b=a; System.out.println("After assigning"); System.out.println("a:" +a ); System.out.println("b:" +b ); b.clear(); System.out.println("after clearing"); System.out.println("a:" +a ); System.out.println("b:" +b ); } public static void main(String[] args) { SetOperation sd = new SetOperation(); sd.assignAndClear(); } } 
+4
source share
2 answers

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); 
+4
source

You rewrite the reference to the memory cell of the original hash in b . You need to copy elements a to b not assign a to b .

Try:

  b = new HashSet<Integer>(a); 
+2
source

Source: https://habr.com/ru/post/1439667/


All Articles