Java 如何向数组中添加接收时可能为空的信息(作为函数参数)

Java 如何向数组中添加接收时可能为空的信息(作为函数参数),java,arrays,pass-by-reference,pass-by-value,Java,Arrays,Pass By Reference,Pass By Value,我有一个返回long数组所需的方法 long[] mainMethod() { //create the resultant array long[] result = null; method1(result); // Their job is to append new long values to the array method2(result); } 我希望做这样的事情: // Update the result array

我有一个返回long数组所需的方法

long[] mainMethod() {

     //create the resultant array 
     long[] result = null;

     method1(result);   // Their job is to append new long values to the array
     method2(result);
}
我希望做这样的事情:

    // Update the result array
    int origLen = (result == null) ? 0 : result.length;
    long[] newResult = new long[origLen + 4];

    if (origLen != 0) {
        newResult = Arrays.copyOf(result, origLen + 4);
    }

    newResult[origLen + 0] = someLong;
    newResult[origLen + 1] = someLong;
    newResult[origLen + 2] = someLong;
    newResult[origLen + 3] = someLong;
    result = newResult;
当我意识到java按值传递引用时,我不能在这里更改引用。如果无法更改这些方法的定义(要生成的结果将作为参数传递,因为存在其他返回值),如何更新原始数组??有人告诉我不要使用ArrayList(我可以更新获取ArrayList的方法,但有人告诉我使用ArrayList并最终返回long数组是愚蠢的)

我想我可以先分配4个长值,然后继续传递和复制,就像:

    result = Arrays.copyOf(result, origLen + 4);
我认为这可以工作,但是如何检查由实际的,
main方法返回的数组是否包含一些有用的信息呢?现在,我正在检查它是否为空

提前感谢。

您可以这样做:

long[] mainMethod() {

     //create the resultant array 
     long[] result = null;

     result = method1(result);   // Their job is to append new long values to the array
     result = method2(result);
}

只需确保方法1和方法2返回long[]。

如果需要动态调整大小的数据结构,请不要使用数组

在这种情况下,您可以非常轻松地使用
LinkedList

List<Long> result = new LinkedList<>();
method(result); // adds to result
method(result); // adds more to result

Long[] array = result.toArray(new Long[result.size()]);
List result=newlinkedlist();
方法(结果);//增加结果
方法(结果);//为结果添加更多内容
Long[]数组=result.toArray(新的Long[result.size()]);

有人告诉我不要使用ArrayList,不要听他们的。使用ArrayList,最后将其转换为长数组。这一点都不傻。我已经从这些方法中返回了一些信息,所以我不能返回数组。这真是个麻烦。虽然我想知道为什么,如果你已经有了从method1和method2返回的信息,你没有给它们分配任何变量吗?如果不使用这些信息,您还可以重构这些方法以返回结果。使用ArrayList和LinkedList有什么区别?这两种方法中的任何一种都能解决我们的唯一需求,那就是可扩展部分??一个
ArrayList
在内部使用一个数组。因此,当它必须动态增长时,它必须首先将其元素复制到一个新的、更大的数组中。在极端情况下,这可能会影响性能。请看这里: