如何在 Java 中通过引用传递可变参数 [英] How to pass varargs by reference in Java

查看:21
本文介绍了如何在 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屋!

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