Reputation: 314
Below is a sample of code I am using to add to an array. Basically if I understand correctly currently I am copying an Array into a List, then adding to the list and copying back to an array. It seems like there should be a better way to do this.
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));
stringList.add(other);
npMAROther.setOtherArray(stringList.toArray(new String[0]));
I just edited my question for a bit more clarity. The for loop previously seen wasn't exactly needed in regards to my original question. I am simply looking for a more efficient way to add to an array.
Upvotes: 3
Views: 3081
Reputation: 9450
There are many ways to combine arrays in O(N) time. You could do something more readable than your code, for instance :
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"}
Upvotes: 0
Reputation: 2208
Supposing you want to use an array, not a list and that all the array elements are filled, you would copy the array in an array that has the size of the original array plus the string list size, then append the list elements at the end of the array:
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;
}
Upvotes: 2
Reputation: 9414
If this is something that is done frequently, consider using a list. However...
You can easily add a single element to the end of an array like this.
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);
}
You can also make it a method.
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;
}
Upvotes: 4