Is there a more efficient way to add to an array?

Below is a sample code that I am using to add to an array. Basically, if I understand correctly, I am currently copying the array to a list and then adding to the list and copying back to the array. There seems to 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 clarity. The for loop I saw earlier was not exactly necessary in relation to my original question. I'm just looking for a more efficient way to add to an array.

+3


source to share


3 answers


If this is done often, consider using a list. However...

You can easily add one element to the end of the 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 do it with the 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;
}

      

+4


source


Suppose you want to use an array, not a list, and that all the elements of the array are filled, you have to copy the array into an array with the size of the original array plus the size of the string list, and then add 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;
}

      

+2


source


There are many ways to combine arrays in O (N) time. You could do something more readable than your code, like:

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"}

      

0


source







All Articles