別名 (Aliasing)
別名,顧名思義,是有別於現在名字的另一個名字,但指的是不是同一個人或事物呢?比如,你上學的時候同學有沒有給你起什么外號?如果有的話,你的名字和同學給你起的外號是不是都指的是你自己?肯定是的哦。
Java中的別名亦類似,Java 給某個變量起別名,其實就是賦值語句(Assignment Statement,如 b = a),只是這里的** 值 ** 要視情況而定。
一般分兩種情況:
1。基本數據類型 (Primitive Type):這個是真正的賦值。
2。引用類型 (Reference Type):這個則是復制一份引用。
讓我們分別開看一下。
基本數據類型 (Primitive Type)
if x and y are variables of a primitive type, then the assignment of y = x copies the value of x to y.
如果 x 和 y 是基本數據變量,那么賦值語句 y = x 是將 x 的 值 復制給 y。
這個比較好理解,代碼示例:
int a = 2;
int b = a;
int c = 2;
System.out.println("a: "+ a);
System.out.println("b: "+ b);
System.out.println("c: "+ c);
System.out.println("a == b is: " + (a==b));
System.out.println("a == c is: " + (a==c));
運行結果:
a: 2
b: 2
c: 2
a == b is: true
a == c is: true
引用類型(Reference Type)
For reference types, the reference is copied (not the value)
對於引用類型的 x 和 y,y = x 表示將 x 的 引用復制一份給 y (不是 x 的值哦)
比如,給定一個數組 a,給它起一個別名 b(b = a),二者其實都指向 a 所指向的同一個對象。
代碼演示:
int[] a = {1,2,3};
int[] b = a;
int[] c = {1,2,3};
System.out.println("a: "+ a);
System.out.println("b: "+ b);
System.out.println("c: "+ c);
System.out.println("a == b is: " + (a==b));
System.out.println("a != c is: " + (a!=c));
運行結果可以看出,b 是 a 的 別名,a 和 b 指向的是同一對象地址(1218025c),a 和 c 則不同。
a: [I@1218025c
b: [I@1218025c
c: [I@816f27d
a == b is: true
a != c is: true
在內存中的位置大概是這樣的:
引申思考:
1。Java 中數組有個clone()方法,比如 b = a.clone(); 這與前面的 b=a 是否一樣?為什么?
2。Java 別名的設計目的是什么?