Java 别名(Aliasing)

别名 (Aliasing)

别名,顾名思义,是有别于现在名字的另一个名字,但指的是不是同一个人或事物呢?比如,你上学的时候同学有没有给你起什么外号?如果有的话,你的名字和同学给你起的外号是不是都指的是你自己?肯定是的哦。

Paste_Image.png

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

在内存中的位置大概是这样的:
Paste_Image.png

引申思考:

1。Java 中数组有个clone()方法,比如 b = a.clone(); 这与前面的 b=a 是否一样?为什么?

2。Java 别名的设计目的是什么?

posted on 2017-04-16 11:09  不忘初心mao  阅读(6161)  评论(0编辑  收藏  举报

导航