zoukankan      html  css  js  c++  java
  • 按引用与按值传递的示例

    二、数据作为方法参数示例代码:

    // PassArray.java

    // Passing arrays and individual array elements to methods

    public class PassArray {

    public static void main(String[] args) {

    int a[] = { 1, 2, 3, 4, 5 };

    String output = "The values of the original array are: ";

    for (int i = 0; i < a.length; i++)

    output += "   " + a[i];//输出原始数组的值

    output += " Effects of passing array " + "element call-by-value: "

    + "a[3] before modifyElement: " + a[3];//输出a[3]的原始数据

    modifyElement(a[3]);//定义一个方法,引用传递

    output += " a[3] after modifyElement: " + a[3];

    output += "  Effects of passing entire array by reference";

           //按值传送数组类型方法参数

    modifyArray(a); // array a passed call-by-reference

     

    output += " The values of the modified array are: ";

    for (int i = 0; i < a.length; i++)

    output += "   " + a[i];

    System.out.println(output);

    }

    public static void modifyArray(int b[]) {

    for (int j = 0; j < b.length; j++)

    b[j] *= 2;//方法的使用,改变了组数元素的值,直接修改了原始的数组元素

    }

    public static void modifyElement(int e) {

    e *= 2;

    }

    }

    运行结果:

    分析:引用传递跟值传递方法的区别:

      前者是若直接在方法体改变a[3]的值,最后输出的就是更改后的的值;后者的方法体修改的仅是原始数组数组元素的一个拷贝。

      按引用传递与按值传送数组类型方法参数的最大关键在于:

    使用前者时,如果方法中有代码更改了数组元素的值,实际上是直接修改了原始的数组元素。

    使用后者则没有这个问题,方法体中修改的仅是原始数组元素的一个拷贝。

  • 相关阅读:
    ASP.NET Core的配置信息
    ASP .NET Core 建立列表和表单View
    ASP.NET Core 如何使用Mvc相关技术建立Controller、Tag Helper (下)
    MySQL日志突然暴涨
    MySQL函数索引及优化
    MySQL统计库表大小
    MySQL8.0窗口函数实践及小结
    MySQL按指定字符合并及拆分
    分享2个近期遇到的MySQL数据库的BUG案例
    mysql大表在不停机的情况下增加字段该怎么处理
  • 原文地址:https://www.cnblogs.com/1995-qxl/p/4922975.html
Copyright © 2011-2022 走看看