diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java new file mode 100644 index 0000000000..121d240a85 --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class MovingItemsInArrayListUnitTest { + + @Test + public void givenAList_whenManuallyReordering_thenOneItemMovesPosition() { + ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); + + String removed = arrayList.remove(3); + arrayList.add(2, removed); + + ArrayList expectedResult = new ArrayList<>(Arrays.asList("one", "two", "four", "three", "five")); + assertEquals(expectedResult, arrayList); + } + + @Test + public void givenAList_whenUsingSwap_thenItemsSwapPositions() { + ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); + + Collections.swap(arrayList, 1, 3); + + ArrayList expectedResult = new ArrayList<>(Arrays.asList("one", "four", "three", "two", "five")); + assertEquals(expectedResult, arrayList); + } + + @Test + public void givenAList_whenUsingRotateWithPositiveDistance_thenItemsMoveToTheRight() { + ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); + + Collections.rotate(arrayList, 2); + + ArrayList expectedResult = new ArrayList<>(Arrays.asList("four", "five", "one", "two", "three")); + assertEquals(expectedResult, arrayList); + } + + @Test + public void givenAList_whenUsingRotateWithNegativeDistance_thenItemsMoveToTheLeft() { + ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); + + Collections.rotate(arrayList, -2); + + ArrayList expectedResult = new ArrayList<>(Arrays.asList("three", "four", "five", "one", "two")); + assertEquals(expectedResult, arrayList); + } +}