zoukankan      html  css  js  c++  java
  • 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 别名的设计目的是什么?

  • 相关阅读:
    D. The Fair Nut and the Best Path 树形dp (终于会了)
    (二)网络流之最大流
    网络流(知识点) 一 终究还是躲不掉
    dp 优化 F2. Pictures with Kittens (hard version)
    da shu mo ban
    AtCoder Regular Contest 090 F
    Codeforces 918D MADMAX 图上dp 组合游戏
    Codeforces 918C The Monster
    AtCoder Regular Contest 090 C D E F
    poj 3623 Best Cow Line, Gold 后缀数组 + 贪心
  • 原文地址:https://www.cnblogs.com/learnbydoing/p/6718214.html
Copyright © 2011-2022 走看看