If we want to concatenate current collection elements to same collection ex: if current collection contains {1,2,3} how to write logic in apex to make its value {1,2,3,1,2,3} without using any extra collection. Below is the implementation of similar logic in c++ using vector. Can we use list/map collections as an alternative to vector?

 vector<int> getConcatenation(vector<int>& nums) {
    int listSize = nums.size();
    for(int i=0;i<listSize;i++)
    return nums;

Tried similar logic (below) in apex using list but got : List index out of bound error

public static List<Integer> concatenationOfArray(List<Integer>originalIntegerArray)
    Integer listSize = originalIntegerArray.size();
    for(Integer i=0;i<listSize;i++)
        originalIntegerArray[listSize+i] = originalIntegerArray[i];
    return originalIntegerArray;

If you have [1, 2, 3] and want to end up with [1, 2, 3, 1, 2, 3], then the simplest approach would be to use .addAll() and pass the current list.

List<Integer> myList = new List<Integer>{1, 2, 3};
system.debug(myList); // prints (1, 2, 3, 1, 2, 3)

The more literal translation of your code in Apex would be to use the List.add method:

Integer[] myList = new Intger[] { 1, 2, 3 };
for(Integer index = 0, size = myList.size(); index < size; index++) {

Where add behaves identically to push_back, though the underlying implementation is likely different.

In your specific case, I would still recommend using addAll, as given by Derek, for performance reasons. However, I wanted to bring this to your attention in case you have need for it in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.