-2

In general, for variables of the same type, A will not be affected even if B changes after entering B into A.

However, in case of Vector type object, if B is input to A object and B.clear () or B.removeAllElements() is executed, A is also initialized to null value.

Please explain why this is happening Also, how can I disconnect shared objects of vector objects A and B?

public class test {

public static void main(String[] args) {

        int A = 1;
        int B;
        B = A;
        A = 0;

        Vector<String> goPathNode = new Vector<String>();
        Vector<String> tempGoPath = new Vector<String>();

        tempGoPath.add("A");
        tempGoPath.add("B");
        tempGoPath.add("C");
        //goPathNode.add("A");
        //goPathNode.add("B");
        //goPathNode.add("C");
        goPathNode = tempGoPath;
        tempGoPath.clear();
        //goPathNode.removeAllElements();

      }
}
Coolluck
  • 3
  • 3
  • Please do not post images of code. Cut and paste it into the question itself. – Stephen C Dec 17 '19 at 03:04
  • Why? I used an image to show how the results came out. Is there a problem with clicking images? Anyway, I fixed it as you wished so someone could solve the problem. – Coolluck Dec 17 '19 at 04:23
  • Primitive ints have different semantics then reference types. In your example, by doing that final assignment, you end up with ONE vector object, but you have TWO references (variables) pointing towards that one object. That is like: you have a first name and a last name. You can be addressed by either of that names. But it is still just one person. – GhostCat Dec 17 '19 at 04:32
  • *"Why?"* - Please read [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/questions/303812) – Stephen C Dec 17 '19 at 04:57
  • I understand, thank you for pointing out. – Coolluck Dec 17 '19 at 05:29

1 Answers1

2

variable goPathNode becomes reference of tempGoPath. So if you clear tempGoPath then goPathNode will get cleared too.

Call clone() function if u want them to be seperate

goPathNode = tempGoPath.clone();

Hope this helps

  • Thank you for your help. If run it as you told me, the problem is "Type mismatch: cannot convert from Object to Vector ". So I solved it by modifying "goPathNode = (Vector ) tempGoPath.clone ();". – Coolluck Dec 17 '19 at 04:51