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();
}
}
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
awill get reflected inb.This is true for
anyMutable Object.But not for
ImmutableObjects.For E.g, Consider the case for
String: -In the above case, the change is not reflected to all the reference, because
Stringsare immutable. So any change you make to String will create anew object.But, if you have
mutable object.: -If you want to create a copy of your Set. Do it like this: -