From efe6e76d97322fb03ba1b8c0ca58d80fde3b8cae Mon Sep 17 00:00:00 2001 From: Kilian Schneider <48420258+Basler182@users.noreply.github.com> Date: Mon, 14 Nov 2022 19:48:39 +0100 Subject: [PATCH] basler1337@gmail.com feat add element to array list at specific index (#13025) * feat add element to array list at specific index * add unit test for add element at index --- .../AddElementAtIndexUnitTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/addelementatindex/AddElementAtIndexUnitTest.java diff --git a/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/addelementatindex/AddElementAtIndexUnitTest.java b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/addelementatindex/AddElementAtIndexUnitTest.java new file mode 100644 index 0000000000..697bc7a711 --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/addelementatindex/AddElementAtIndexUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.list.addelementatindex; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +class AddElementAtIndexUnitTest { + + @Test + void givenArrayList_whenAddElementAtIndex_thenGetExpectedElementAtIndex() { + List integers = new ArrayList<>(); + // add some elements + integers.add(5); + integers.add(6); + integers.add(7); + integers.add(8); + assertThat(integers.get(0)).isEqualTo(5); + assertThat(integers.get(1)).isEqualTo(6); + assertThat(integers.get(2)).isEqualTo(7); + assertThat(integers.get(3)).isEqualTo(8); + // add an element at a specific index + integers.add(1, 9); + assertThat(integers.get(0)).isEqualTo(5); + assertThat(integers.get(1)).isEqualTo(9); + assertThat(integers.get(2)).isEqualTo(6); + assertThat(integers.get(3)).isEqualTo(7); + assertThat(integers.get(4)).isEqualTo(8); + // sort the array list + integers.sort(Integer::compareTo); + assertThat(integers.get(0)).isEqualTo(5); + assertThat(integers.get(1)).isEqualTo(6); + assertThat(integers.get(2)).isEqualTo(7); + assertThat(integers.get(3)).isEqualTo(8); + assertThat(integers.get(4)).isEqualTo(9); + } +} \ No newline at end of file