【问题标题】:How to add info to array which may be null on receipt (as a function argument)如何将信息添加到收到时可能为空的数组(作为函数参数)
【发布时间】:2013-09-11 13:59:48
【问题描述】:

我有一个方法需要返回一个 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);

我认为这可行,但是我如何检查实际返回的数组,mainMethod 是否包含一些有用的信息?截至目前,我正在检查它是否为空..

提前致谢。

【问题讨论】:

  • 有人告诉我不要使用 ArrayList 不要听他们的。
  • 使用 ArrayList 并最终将其转换为 long 数组。没什么可笑的。

标签: java arrays pass-by-reference pass-by-value


【解决方案1】:

你可以这样做:

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[]。

【讨论】:

  • 我已经从这些方法返回了一些信息,所以我无法返回数组。
  • 那真是太糟糕了。尽管我想知道为什么,如果您已经从方法 1 和方法 2 返回了信息,您是否没有为它们分配任何变量?如果您不使用信息,您不妨重构这些方法以返回结果。
【解决方案2】:

如果您想要一个可动态调整大小的数据结构,请不要使用数组。

在这种情况下,您可以非常轻松地使用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()]);

【讨论】:

  • 使用 ArrayList 和 LinkedList 有什么区别?我们唯一通过这两种方法解决的需求是可增长部分?
  • 一个ArrayList 内部使用一个数组。因此,当它必须动态增长时,它必须首先将其元素复制到一个新的、更大的数组中。在极端情况下,这可能会损害性能。在这里阅读:stackoverflow.com/questions/11667955/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多