Swap the order of adding and deleting the elements to make it work. Note that whenever you remove an element from an ArrayList
, all the indices after that position get decreased by one place; in other words, all the elements after that position get shifted to the left (or towards the beginning) by one position.
Demo:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
int sourceIndex = list.indexOf("A");
int destIndex = list.indexOf("C");
list.remove(sourceIndex);
list.add(destIndex, "A");
System.out.println(list);
}
}
Output:
[B, C, A, D]
There can be many other ways to do it e.g.
Rotate and swap:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
Collections.rotate(list, 3);
System.out.println(list);
Collections.swap(list, 2, 3);
System.out.println(list);
}
}
Output:
[B, C, D, A]
[B, C, A, D]
Just swap:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C", "D");
Collections.swap(list, 0, 1);
System.out.println(list);
Collections.swap(list, 1, 2);
System.out.println(list);
}
}
Output:
[B, A, C, D]
[B, C, A, D]