zoukankan      html  css  js  c++  java
  • 关于JAVA中包装类的是什么类型传递这个问题的笔记

    背景知识:

    如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值。如果在函数中改变了副本的值不会改变原始的值.

    如果参数类型是引用类型,那么传过来的就是这个参数的引用,这个引用存放的是参数的对象地址。如果在函数中没有改变这个参数的引用地址,而是改变了地址中的 值,那么在函数内的改变会影响到传入的参数。

    如果在函数中改变了参数的引用地址,如new一个,那么函数中的局部变量就指向了一个新的对象地址,此时传入的参数还是指向原来的地址,所以不会改变参数的值(如下图)。

     

    /**
     * 
     * @author ZHOUMI2
    * 转自:http://blog.csdn.net/wuya814070935/article/details/49250773
    */ public class Test { public static void test1(Integer num){ num = new Integer(5); } public static void test2(String str){ str.replace("1", "4"); } public static void main(String[] args) { Integer num = new Integer(1); test1(num); // 输出结果为1 System.out.println(num.intValue()); String str = new String("123"); test2(str); // 输出结果为123 System.out.println(str); } }

    分析: 上述程序很容易让人误以为String类型和包装类型是值传递。

    其实: String类型和包装类型都是对象类型,所以必然是引用传递。

          但是由于String类和包装类都被设定成不可变的,没有提供value对应的setter方法,而且很多都是final的,我们无法改变其内容,所以导致我们看起来好像是值传递。

  • 相关阅读:
    第七周 10.11-10.17
    第六周 10.4-10.10
    2015 ACM/ICPC Asia Regional Hefei Online
    cryptopals S1-6
    cryptopals S1-5
    cryptopals S1-4
    Cryptopals S1-3
    Crptopals S1-2
    Crptopals S1-1
    anaconda the procedure entry point openssl_sk_new_reserve could not be located in the dynamic link library libssl-1_1-x64.DLL
  • 原文地址:https://www.cnblogs.com/xujanus/p/7194410.html
Copyright © 2011-2022 走看看