Output Parameters in Java

2020-04-08 12:40发布

With a third party API I observed the following.

Instead of using,

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

it uses something like

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?

8条回答
贼婆χ
2楼-- · 2020-04-08 13:14

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!";
}

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.

查看更多
欢心
3楼-- · 2020-04-08 13:23

I disagree with Jasper: "In my opinion, this is a really ugly and bad way to return more than one result". In .NET there is a interesting construct that utilize the output parameters:

bool IDictionary.TryGet(key, out value);

I find it very usefull and elegant. And it is the most convenient way to aks if an item is in collection and return it at the same time. With it you may write:

object obj;
if (myList.TryGet(theKey, out obj))
{
  ... work with the obj;
}

I constantly scold my developers if I see old-style code like:

if (myList.Contains(theKey))
{
  obj = myList.Get(theKey);
}

You see, it cuts the performance in half. In Java there is no way to differentiate null value of an existing item from non-existance of an item in a Map in one call. Sometimes this is necessary.

查看更多
登录 后发表回答