English 中文(简体)
java startner - 是一个引用的阵列列表调用
原标题:java beginner- is an arraylist call by reference

在 java 程序里, 我想要用调用一个函数来修改 3 个阵列列表变量 。

我是否正确地认为,如果我将这3个阵列列表作为参数传递到该函数, 那么所有3个列表都可以在函数中修改 。 或者我是否必须在一个单独的函数中修改每个阵列列表, 并指定该阵列列表为返回值, 以确保它被修改 。

最佳回答

我是否正确地认为,如果我通过这3个阵列列表作为该函数的参数,那么所有3个列表都可以在函数中修改?

一句话,是的。

值得指出的是,您问题的标题中的“ 引用” 术语不完全正确。 在 Java 中,一切都被 < em> by value , 包括对象引用。 事实上,三个 < code > ArrayList 参数是引用 < em> 自己 < / em >, 对列表所做的任何更改都会回传到调用方 。

问题回答

是的, 您可以通过 3 < code> ArrayList 3 参数作为该方法的参数。 它们被像任何其他对象一样对待 。

至于是否返回另一个 ArrayList , 这在很大程度上取决于该方法要做什么 。

以下代码的工作方式如“参考调用”:

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);
}
}

产出是:

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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签