Java 中的列表作为输出参数

Ram*_*ami 4 java list function-call output-parameter

我正在尝试编写一个以 List 对象作为输出参数的 Java 函数。

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

在此之前,我调用函数,声明 myList 如下:

List myList=null;
Run Code Online (Sandbox Code Playgroud)

然后我调用该函数

myFunction(x,y,myList)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试操作 myList 时,我发现 myList 仍然为空。

我确信anotherList我的函数代码中的变量不为空,并且我确信该subList函数返回一个非空列表。

原因是什么?如何在 Java 函数中传递 List 作为输出参数?

Mar*_*aux 5

Java 总是使用按值传递。这意味着操作传递的变量不会影响调用者传递的变量。

为了解决您的问题,有一些可能性:

  • 返回子列表:

    List myFunction(int x, int y) { return anotherList.subList(....);}
    
    Run Code Online (Sandbox Code Playgroud)

    我知道这种方式可以消除你的布尔返回值。

  • 创建一个结构体来保存指向 List 的指针。

    class Reference <T>
    {
        public T ref;
    }
    
    boolean myFunction(int x, int y, Reference<List> listRef)
    {
          listRef.ref = anotherList.subList(....);
          return true;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建一个结构来保存您希望该方法返回的所有输出:

    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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 或者最简单的方法:传递一个初始化的 List 而不是 null 并让函数添加子列表,就像 Attila 建议的那样。