Java中的输出参数

Cha*_*ara 4 java api methods output-parameter

使用第三方API,我观察到以下内容.

而不是使用,

public static string getString(){
   return "Hello World";
}
Run Code Online (Sandbox Code Playgroud)

它使用类似的东西

public static void getString(String output){

}
Run Code Online (Sandbox Code Playgroud)

我正在分配"输出"字符串.

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

Ada*_*kin 21

你的例子中有些东西是不对的.

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

class Holder<T> {
    public Holder(T value) {
        this.value = value;
    }
    public T value;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以绕过持有人:

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"
}
Run Code Online (Sandbox Code Playgroud)


Bom*_*mbe 5

That example is wrong, Java does not have output parameters.

One thing you could do to emulate this behaviour is:

public void doSomething(String[] output) {
    output[0] = "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)

But IMHO this sucks on multiple levels. :)

If you want a method to return something, make it return it. If you need to return multiple objects, create a container class to put these objects into and return that.