简体   繁体   English

java beginner-是一个arraylist通过引用调用

[英]java beginner- is an arraylist call by reference

In a java program, I want 3 arraylist variables to be modified by a call to a single function. 在java程序中,我希望通过调用单个函数来修改3个arraylist变量。

Am I correct in thinking that if I pass these 3 arraylists as parameters to that function, then all 3 can be modified within the function? 我是否正确地认为如果我将这3个arraylists作为参数传递给该函数,那么所有3个都可以在函数内修改? Or will I have to modify each arraylist in a separate function, and specify that array list as the return value, to ensure that it is modified. 或者我是否必须在单独的函数中修改每个arraylist,并将该数组列表指定为返回值,以确保它被修改。

Am I correct in thinking that if I pass these 3 arraylists as parameters to that function, then all 3 can be modified within the function? 我是否正确地认为如果我将这3个arraylists作为参数传递给该函数,那么所有3个都可以在函数内修改?

In a word, yes. 总之,是的。

It is worth noting that the "by reference" terminology in the title of your question is not exactly right. 值得注意的是,问题标题中的“引用”术语并不完全正确。 In Java, everything is passed by value , including object references. 在Java中,所有内容都按值传递,包括对象引用。 It is the fact that the three ArrayList parameters are references themselves that makes any changes made to the lists propagate back to the caller. 事实上,三个ArrayList参数本身就是引用这使得对列表所做的任何更改都会传播回调用者。

Yes, you can pass the 3 ArrayList s as parameters to the method. 是的,您可以将3个ArrayList作为参数传递给方法。 They are treated like any other object. 它们被视为任何其他对象。

As to whether to return another ArrayList , this depends a lot on what the method has to do. 至于是否返回另一个ArrayList ,这很大程度上取决于该方法必须做什么。

The following code works like "call by reference": 以下代码的工作方式类似于“按引用调用”:

package arrayList;

import java.util.ArrayList;

public class CallByValueReference {

class myObject {
    String str;

    public myObject(String str) {
        super();
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "myObject [str=" + str + "]";
    }   
}

ArrayList<myObject> strArray = new ArrayList<myObject>();

public static void main(String[] args) {
    new CallByValueReference().test();
}

private void test() {
    strArray.add(new myObject("entry1") );
    System.out.println(strArray);
    strArray.get(0).setStr("entry2");
    System.out.println(strArray);
}
}

The output is: 输出是:

[myObject [str=entry1]]
[myObject [str=entry2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM