Assigning one set to another and when Clear is performed.Both the sets are getting cleared

3.4k views Asked by At

1.Initially created two sets. 2.Added elements to one set. 3.Assigned one set to another. 4.If clear is called on one set,both the sets are getting cleared.

Can anyone help in figuring out 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();
}
}
2

There are 2 answers

3
Rohit Jain On BEST ANSWER

When you assign one set to another, new set is not created, rather a new reference is created that points to the existing set. So, whatever change you make to the set using a will get reflected in b.

This is true for any Mutable Object.

But not for Immutable Objects.

For E.g, 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 is not reflected to all the reference, because Strings are immutable. So any change you make to String will create a new object.

But, if you have 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 Set. Do it like this: -

Set<String> set1 = new HashSet<String>();
Set<String> set3 = new HashSet<String>(set1);
0
Lews Therin On

You overwrite the reference to the memory location of the original hashset in b. You need to copy the elements of a into b not assign a to b.

Try:

 b = new HashSet<Integer>(a);