[英]Is there a more efficient way to add to an Array?
下面是我用来添加到数组的代码示例。 基本上,如果我理解正确的话,我正在将一个数组复制到一个List中,然后添加到列表并复制回一个数组。 似乎应该有更好的方法来做到这一点。
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));
stringList.add(other);
npMAROther.setOtherArray(stringList.toArray(new String[0]));
我只是为了更清晰一点地编辑了我的问题。 之前看到的for循环对于我原来的问题并不是完全需要的。 我只是在寻找一种更有效的方法来添加到数组中。
如果这是经常完成的事情,请考虑使用列表。 然而...
您可以轻松地将单个元素添加到数组的末尾。
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;
}
假设您要使用数组而不是列表并且所有数组元素都已填充,您可以将数组复制到具有原始数组大小和字符串列表大小的数组中,然后在末尾追加列表元素数组:
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;
}
在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"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.