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]的值,最后输出的就是更改后的的值;后者的方法体修改的仅是原始数组数组元素的一个拷贝。

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

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

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

  • 相关阅读:
    JS 中 new 操作符
    js清除浏览器缓存的几种方法
    一个自定义分享按钮
    解决windows下nginx中文文件名乱码
    sublime text 3 添加 javascript 代码片段 ( snippet )
    transition动画最简使用方式
    hammerjs jquery的选项使用方法,以给swipe设置threshold和velocity为例
    sublime text 3 的emmet 添加自定义 html 片段
    解决 placeholder 垂直不居中,偏上的问题
    Sublime Text 3 配置 sass
  • 原文地址:https://www.cnblogs.com/1995-qxl/p/4922975.html
Copyright © 2011-2022 走看看