Java:将数组作为方法中的引用类型 [英] Java: arrays as reference types, in methods

查看:133
本文介绍了Java:将数组作为方法中的引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从C ++迁移到Java,并且在理解数组如何在Java中如何在其创建方法之外持续存在问题时遇到了一个问题.看看下面的简单代码:

I am moving from C++ to Java, and I have a problem understanding how, in Java, an array lasts outside the method in which it was created. Take a look at this simple code below:

public static int[] arrayMethod(){
    int[] tempArray = {1, 2, 3, 4};
    return tempArray;
}

public static void main(String[] args){
    int arr[] = arrayMethod();
    for(int i : arr){
        System.out.println(i);
    }
}

在C ++中,除非使用new运算符动态分配该数组,否则该数组在调用后将不存在,因为它是在方法中本地创建的.据我了解,Java总是按值传递,而数组是引用类型,因此我的c ++逻辑会告诉我,我正在返回对本地创建的数组的引用.我想念什么?

In C++, unless the array is dynamically allocated with the new operator, the array would not exist after the call, because it was created locally in the method. As I understand it, Java is always pass by value, and arrays are reference types, so my c++ logic would tell me that I am returning a reference to a locally created array. What am I missing?

推荐答案

也许这可以帮助您理解.

Perhaps this will help you understand.

在Java中,这是

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

表示完全与此相同:

int[] tempArray = new int[]{1, 2, 3, 4};

第一种形式是隐式 new.

在Java中,所有数组都是堆对象/引用.当数组传递给方法时,其处理方式与处理任何引用相同.即引用是按值传递的. (不,这不是按引用呼叫"或按引用传递",因为这些术语已被正确理解.)

In Java, all arrays are heap objects / references. And when an array is passed to a method, it is handled the same way that any reference is handled; i.e. the reference is passed by value. (And no, this is NOT "call by reference" or "pass by reference" as those terms are properly understood.)

这篇关于Java:将数组作为方法中的引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆