Search code examples
javalistfunction-calloutput-parameter

List as output parameter in Java


I am trying to write a Java function which has List object as output parameter.

boolean myFunction(int x, in y, List myList)
{
    /* ...Do things... */
    myList=anotherList.subList(fromIndex, toIndex);
    return true;
}

Before that I call the function I declare myList as follow:

List myList=null;

Then I call the function

myFunction(x,y,myList)

But when I try to manipulate myList, I find that myList is still null.

I am sure the variable anotherList in my function code is not null and I am sure that the subList function return a non-empty List.

What is the reason, and how can pass a List as output parameter in a Java function?


Solution

  • Java always uses pass by value. This means that manipulating a passed variable won't affect the variable that was passed by the caller.

    In order to solve your problem there are some possibilities:

    • Return the sublist:

      List myFunction(int x, int y) { return anotherList.subList(....);}
      

      I know that this way gets rids of your boolean return value.

    • Create a structure that holds the pointer to the List and.

      class Reference <T>
      {
          public T ref;
      }
      
      boolean myFunction(int x, int y, Reference<List> listRef)
      {
            listRef.ref = anotherList.subList(....);
            return true;
      }
      
    • Create a structure that holds all the output you want the method to return:

      class MyFunctionOutput
      {
           List list;
           boolean b;
      }
      
      MyFunctionOutput myFunction(int x, int y)
      {
           MyFunctionOutput out = new MyFunctionOutput();
           out.list = anotherList.subList(....);
           out.b = true;
           return out;
      }
      
    • Or the most easy way: pass an initialized List instead of null and let the function add the sublist, like Attila suggested.