zoukankan      html  css  js  c++  java
  • java中传值与传引用

      1、一句话出自:think in Java,"When you're passing primitives into a method, you get a distinct copy of the primitive.

    When you're passing a reference into a method, you get a copy of the reference.(如果java是传值,则传递的是值得副本;

    如果java是传引用,则传递的是引用的副本。)

      2、对基本数据类型而言,就是把自己复制一份传递,即使副本变了,自己也不变。而对对象类型而言,它传的是引用

    的副本。为什么不直接传对象?浪费内存且速度慢。

    下面看个例子:

    1、传值

     1 public class Test{
     2         public static void test(boolean test){
     3               tets = !test;
     4               system.out.println("In test (boolean) : test=" + test);
     5         }
     6          public static void main(String[] args){
     7                boolean test = true;
     8                system.out.println("before test(boolean) : test=" +test)
     9                test(test);
    10                system.out.println("after test(boolean) : test=" +test)
    11          }
    12 }       
        运行结果:
             before test(boolean) : test=true
             In test (boolean) : test=false
    before test(boolean) : test=true

    2、传引用

    public class Test{
             public static void test(StringBuffer str){
                      str.append(", World!");
             }  
             public static void main(String[] args){
                       StringBuffer string = new StringBuffer("Hello");
                       test(string);
                       system.out.println(string);
             }
    }    
    运行结果:
          Hello,World

    另一种情况

    public class Test{
             public static void test(String str){
                      str = "World";
             }  
             public static void main(String[] args){
                      String string = "Hello";
                      test(string);
                      system.out.println(string);
             }
    }  
    运行结果:
          Hello
    原因:String类是final的,
    str = "World";隐含重新生成一个对象。
    
    

    总结:对于基本数据类型,java是传值的副本;对于一切对象型变量,java是传引用的副本。

  • 相关阅读:
    数组名和指针区别(还有数组退化等)
    无法从“const char *”转换为“char *”
    c语言数组初始化问题
    c语言实现atoi和itoa函数。
    不使用临时变量交换两个整数
    hdu 1282回文数猜想
    Android仿WIN8系统磁贴点击下沉倾斜效果
    Android Studio使用心得
    处理json中影响解析的多余引號
    我也来开发2048之主界面设计
  • 原文地址:https://www.cnblogs.com/xingrui/p/9576820.html
Copyright © 2011-2022 走看看