0

Trying:

List<sObject> list1 = New List<sObject>(has values);  
List<sObject> list2 = New List<sObject>(has no values);  
for (Integer i=0; i<5; i++) {  
    sObject toAdd = list1[i].remove;  
    list2.add(toAdd);
}
  • sry i can't edit. Trying to figure it out.. – Andrew Mayes May 12 '17 at 22:10
  • I've edited your question this time. For future reference, you can use backticks (the key to the left of the 1 key on English qwerty keyboards) to 'inline' code. To make a code block (like I've done for you), each line needs to have 4 spaces at the beginning of the line (plus an empty line above & below). The easiest way to do that is to highlight your code and press ctrl + k (alternatively, pressing the {} button on the top bar of the text editor does the same thing). – Derek F May 12 '17 at 22:16
0

You're close:

for(Integer i = 0; i < 5; i++) {
    list2.add(list1.remove(i));
}

Keep in mind that if your objective is to copy the first five elements, you should count backwards:

for(Integer i = 4; i >= 0; i--) {

Otherwise, you'd end up copying the first, third, fifth, seventh, and ninth element instead.

List.remove returns the element that was removed, so there's no need for an intermediary to hold the value while it transitions from one list to the other.

If you want to retain the original order of those elements, remove the zeroth element each time:

for(Integer i = 0; i < 5; i++) {
    list2.add(list1.remove(0));
}

Or pre-initialize the list and copy the values if you'd like to count backwards, as above:

list2 = new SObject[5];
for(Integer i = 4; i >= 0; i--) {
    list2[i] = list1.remove(i);
}
  • Great thanks! This remove will also take off of the first list correct? so after removing list1.remove(0) then will 0 be null? or shift? – Andrew Mayes May 12 '17 at 22:43
  • @AndrewMayes Yes, remove removes the current element and shifts all elements higher than the removed index down one, and the list's size will be one smaller. – sfdcfox May 12 '17 at 22:45
  • I see now. That is why you should count backwards – Andrew Mayes May 12 '17 at 22:46
  • @AndrewMayes Yes. If the order matters, note that counting backwards would reverse those five elements. If you want the same order, just remove the zeroth element for each of the five times in your loop. – sfdcfox May 12 '17 at 22:49

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.