在Java中输出参数 [英] Output Parameters in 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".
有些类型是可变的,在这种情况下,你可以修改传递给函数的对象。对于不可改变的类型(如字符串
),你就必须建立某种形式的包装类的,你可以绕过来代替:
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屋!