Setting equal in Java: by value or reference?

前端 未结 4 1760
长发绾君心
长发绾君心 2020-12-17 00:29

I did two tests, the first starting with Strings

    String str1 = \"old\";
    String str2 = str1;
    str1 = \"new\";

    System.out.println(         


        
4条回答
  •  遥遥无期
    2020-12-17 00:48

    Your difference is here

    str1 = "new";
    

    vs

    list1.add(1);
    

    In the String example, you are changing references. Changing the reference of str1 does not affect any other variables.

    In the List example, you are invoking a method, which dereferences the reference and accesses the object. Any variables referencing that same object will see that change.

    Here it is

    List list1 = new ArrayList(); // 1
    List list2 = list1; // 2 
    list1.add(1); // 3
    

    looks like this

       1:  list1 ===> object1234
       2:  list1 ===> object1234 <=== list2
       3:  list1 ===> object1234 (internal modification) <=== list2
    

提交回复
热议问题