如何在 Java 中通过引用传递可变参数 [英] How to pass varargs by reference in Java
问题描述
我正在编写一个方法,它接收任意数量的参数并返回修改后的参数.我尝试过使用可变参数但它不起作用,您可以在这里看到代码的简化版本:
I'm writing a method that receives any number of arguments and returns them modified. I have tried with varargs but it doesn't work, here you can see a simplified version of the code:
public static void main(String[] args) {
String hello = "hello";
String world = "world";
addPrefix(hello, world);
System.out.println("hello: " + hello + " world: " + world);
}
public static void addPrefix(String... elements) {
for (int i = 0; i < elements.length; i++) {
elements[i] = "prefix_" + elements[i];
}
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
}
}
打印结果:
prefix_hello
prefix_world
hello: hello world: world
如您所见,在方法内部正确修改了值,但原始变量没有改变.
As you can see, the values are modified correctly inside the method, but the original vars have not changed.
我看过很多页面,比如这里 和 这里 但它似乎 Java 将 vars 的值复制到 Object[]
,因此引用丢失了.
I have looked at many pages like here and here but it seems that Java copies the values of the vars to an Object[]
, so the references are lost.
知道我该怎么做吗?
推荐答案
Java 是 传值.你无法实现你想要的.相反,您可以从 addPrefix()
函数返回修改后的数组.
Java is pass by value. You cannot achieve what you wish. Instead you can return the modified array from addPrefix()
function.
public static void main(String args[]) {
String hello = "hello";
String world = "world";
String[] elements = addPrefix(hello, world);
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
}
}
public static String[] addPrefix(String... elements) {
for (int i = 0; i < elements.length; i++) {
elements[i] = "prefix_" + elements[i];
}
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
}
return elements;
}
和输出
prefix_hello
prefix_world
prefix_hello
prefix_world
这篇关于如何在 Java 中通过引用传递可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!