Array assignment and reference in Java

前端 未结 5 1480
误落风尘
误落风尘 2020-12-11 08:24
public class Test {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = a;
        int[] c = {6, 7, 8};
        a = c;
         


        
5条回答
  •  醉酒成梦
    2020-12-11 08:50

    Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

    Array a is assigned with a new array:

    Array b is assigned to the instance behind a:

    Array c is assigned with a new array:

    And finally a is assigned to the instance behind c, b was not re-assigned and still keeps a reference to the old a:

    Images taken from a visualization on pythontutor.com

提交回复
热议问题