BAEL-5623 reverse list article (#12253)

* reverse list article

* fix the package
This commit is contained in:
Kai Yuan 2022-06-01 05:58:26 +02:00 committed by GitHub
parent aef4affc28
commit fcdf53f3e4
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.list.reverse;
import java.util.List;
public class ReverseArrayList {
private ReverseArrayList() {
throw new RuntimeException("This class cannot be instantiated.");
}
public static <T> void reverseWithRecursion(List<T> list) {
if (list.size() > 1) {
T value = list.remove(0);
reverseWithRecursion(list);
list.add(value);
}
}
public static <T> void reverseWithLoop(List<T> list) {
for (int i = 0, j = list.size() - 1; i < j; i++) {
list.add(i, list.remove(j));
}
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.list.reverse;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
class ReverseArrayListUnitTest {
private static final List<Integer> EXPECTED = new ArrayList<>(Arrays.asList(7, 6, 5, 4, 3, 2, 1));
@Test
void givenArrayList_whenCallReverseMethod_thenListReversedInPlace() {
List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
Collections.reverse(aList);
assertThat(aList).isEqualTo(EXPECTED);
}
@Test
void givenArrayList_whenCallReverseMethod_thenListReversedAsaNewList() {
List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
List<Integer> aNewList = new ArrayList<>(originalList);
Collections.reverse(aNewList);
assertThat(aNewList).isNotEqualTo(originalList)
.isEqualTo(EXPECTED);
}
@Test
void givenArrayList_whenCallReverseWithRecur_thenListReversedInPlace() {
List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
ReverseArrayList.reverseWithRecursion(aList);
assertThat(aList).isEqualTo(EXPECTED);
}
@Test
void givenArrayList_whenCallReverseWithLoop_thenListReversedInPlace() {
List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
ReverseArrayList.reverseWithLoop(aList);
assertThat(aList).isEqualTo(EXPECTED);
}
}