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

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

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

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

  • 相关阅读:
    Centos 6下使用cmake编译安装MariaDB
    mysql索引
    mysql基础指令知识
    git/github安装与使用教程
    Linux目录结构详解
    static关键字的作用(修饰类、方法、变量、静态块)
    Java中重载(overloading)和重写(Overriding)的区别
    @PropertySources和@ImportReSources注解
    @ConfigurationProperties注解和@Value注解的区别
    Java中数组的定义,初始化和使用
  • 原文地址:https://www.cnblogs.com/1995-qxl/p/4922975.html
Copyright © 2011-2022 走看看