public static void main(String[] args) {
Integer a = 1;
Integer b = 0;
b=a;
System.out.println(a);
System.out.println(b);
++a;
System.out.println(a);
System.out.println(b);
}
Run Code Online (Sandbox Code Playgroud)
输出:1 1 2 1
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(1);
a.add(1);
a.add(1);
b=a;
System.out.println(a.size());
System.out.println(b.size());
b.add(2);
System.out.println(a.size());
System.out.println(b.size());
}
Run Code Online (Sandbox Code Playgroud)
输出:4 4 5 5
对于上面的代码,为什么两个对象都不是指同一个内存位置.
情况1 :
public static void main(String[] args) {
Integer a = 1;
Integer b = 0;
b=a; // 2 references a and b point to same Integer object
System.out.println(a);
System.out.println(b);
++a; // now a references to a new integer object with value 2 where as b refers to old integer object with value 1
System.out.println(a);
System.out.println(b);
}
Run Code Online (Sandbox Code Playgroud)
案例2:
同样,两者a都引用并在同一个barrayList 实例上工作。因此,使用一个引用进行的修改也会反映在其他引用中
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |