Java 中的输出参数 [英] Output Parameters in Java

查看:22
本文介绍了Java 中的输出参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过第三方 API,我观察到以下情况.

With a third party API I observed the following.

而不是使用,

public static string getString(){
   return "Hello World";
}

它使用类似的东西

public static void getString(String output){

}

我得到了分配的输出"字符串.

and I am getting the "output" string assigned.

我很好奇实现这种功能的原因.使用这样的输出参数有什么好处?

I am curious about the reason of implementing such functionality. What are the advantages of using such output parameters?

推荐答案

您的示例中有些地方不对.

Something isn't right in your example.

class Foo {

    public static void main(String[] args) {
        String x = "foo";
        getString(x);
        System.out.println(x);
    }

    public static void getString(String output){
        output = "Hello World"
    }
}

在上面的程序中,将输出字符串foo",不是Hello World".

In the above program, the string "foo" will be output, not "Hello World".

有些类型是可变的,在这种情况下,您可以修改传递给函数的对象.对于不可变类型(例如 String),您必须构建某种可以传递的包装类:

Some types are mutable, in which case you can modify an object passed into a function. For immutable types (such as String), you would have to build some sort of wrapper class that you can pass around instead:

class Holder<T> {
    public Holder(T value) {
        this.value = value;
    }
    public T value;
}

然后你可以绕过持有者:

Then you can instead pass around the holder:

public static void main(String[] args) {
    String x = "foo";
    Holder<String> h = new Holder(x);
    getString(h);
    System.out.println(h.value);
}

public static void getString(Holder<String> output){
    output.value = "Hello World"
}

这篇关于Java 中的输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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