public class UnderstandingMemoryManagement1 {
private static boolean flag = false;
public static void main(String[] args) {
Set<String> mainNameSet = getNameSet();
mainNameSet.add("Name-6");
Log.logInfo(getNameSet() == mainNameSet);
Log.logInfo(getNameSet().equals(mainNameSet));
Log.logInfo("------main() END------");
}
public static Set<String> getNameSet() {
Set<String> nameSet = new TreeSet<>();
nameSet.add("Name-1");
nameSet.add("Name-2");
nameSet.add("Name-3");
nameSet.add("Name-4");
Set<String> otherSet = nameSet;
otherSet.add("Name-5");
if (!flag ) {
flag = true;
Log.logInfo(nameSet == otherSet);
Log.logInfo(nameSet.equals(otherSet));
Log.logInfo("------getNameSet() END------");
}
return nameSet;
}
}
When I run the above code why the output is like below -
INFO: true
INFO: true
INFO: ------getNameSet() END------
INFO: false
INFO: false
INFO: ------main() END------
Why second time it is returning false why not true? As far as I know java copies the reference not the object. When it is coping the referenc not the object then it should return true for second case as well. Please explain this to me.