简体   繁体   中英

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.

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? 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.

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?

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. 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.

Yes, you can pass the 3 ArrayList s as parameters to the method. 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.

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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