有没有更高效的方法添加到数组?

3
以下是我正在使用的添加到数组的代码示例。基本上,如果我理解正确,目前我正在将一个数组复制到一个列表中,然后向列表中添加并将其复制回数组。似乎应该有更好的方法来实现这一点。
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));  
        stringList.add(other);
    npMAROther.setOtherArray(stringList.toArray(new String[0]));

我刚刚编辑了我的问题,以便更加清晰。之前看到的for循环并不是针对我的原始问题所必需的。我只是在寻找一种更有效的方法来添加到数组中。


2
为什么要复制所有内容?只需使用列表即可。 - Kon
如果您需要在进行SOAP调用时使用数组,该怎么办? - serge
@Charlie,你是想将两个数组合并成一个吗? - kiruwka
@kiruwka 不,我只是想向数组中添加一个元素。 - Charles S
@CharlieS 在你的代码中,你正在将一个数组的元素附加到另一个数组的末尾(而不是像你注释中说的那样只有一个元素)。我有什么遗漏吗? - kiruwka
@kiruwka 是的,在这段代码中我正在添加元素,但我只是想知道如何添加单个元素,所以我想这段代码并不完全符合我的问题。 - Charles S
3个回答

4
如果这是一个经常需要做的事情,考虑使用列表。然而,您可以像这样轻松地将单个元素添加到数组的末尾。
  final String[] source = { "A", "B", "C" };
  final String[] destination = new String[source.length + 1];
  System.arraycopy(source, 0, destination, 0, source.length);
  destination[source.length] = "D";

  for(final String s : destination) {
     System.out.println(s);
  }

你也可以将它变成一个方法。
public static String[] addToArray(final String[] source, final String element) {
   final String[] destination = new String[source.length + 1];
   System.arraycopy(source, 0, destination, 0, source.length);
   destination[source.length] = element;
   return destination;
}

在这个方法中,为什么你的变量被声明为 final - anon

2

假设您想使用数组而不是列表,并且所有数组元素都已填充,则可以将该数组复制到一个大小为原始数组加上字符串列表大小的数组中,然后在数组末尾附加列表元素:

String[] array = npMAROther.getOtherArray();
List<String> listElementsToAppend = marOther.getOtherListList();

int nextElementIndex = array.length;

// Increase array capacity
array = Arrays.copyOf(array, array.length + listElementsToAppend.size());

// Append list elements to the array
for (String other : listElementsToAppend) {
    array[nextElementIndex++] = other;
}

0

有许多方法可以在O(N)时间内组合数组。例如,您可以做一些比您的代码更易读的事情:

String[] arr1 = {"1", "2"}, arr2 = {"3", "4"};
ArrayList<String> concat = new ArrayList<>(); // empty
Collections.addAll(concat, arr1);
Collections.addAll(concat, arr2);
// concat contains {"1", "2", "3", "4"}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接