gpt4 book ai didi

java - 列表作为Java中的输出参数

转载 作者:搜寻专家 更新时间:2023-11-01 01:22:50 26 4
gpt4 key购买 nike

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

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

在此之前,我调用我声明 myList 的函数如下: 列表 myList=null;然后我调用函数 myFunction(x,y,myList)但是当我尝试操作 myList 时,我发现 myList 仍然是 null。

我确定我的函数代码中的变量“antherList”不为空,并且我确定 subList 函数返回一个非空列表。

这是什么原因,如何在 Java 函数中将 List 作为输出参数传递?非常感谢。

最佳答案

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

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

  • 返回子列表:

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

    我知道这种方式可以摆脱你的 boolean 返回值。

  • 创建一个包含指向 List 和的指针的结构。

    class Reference <T>
    {
    public T ref;
    }

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

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

关于java - 列表作为Java中的输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11581115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com