dupirefr
2020-04-10 21:16:30 +02:00
parent 2510062202
commit e910c0a238
20 changed files with 128 additions and 10 deletions

View File

@@ -0,0 +1,19 @@
## Core Java Arrays - Basic Operations
This module contains articles about basic operations on arrays in Java
Basic operations would cover anything elementary we should expect to be able to achieve on a collection type:
- Adding/Removing elements
- Getting elements
- Iterating
### Relevant Articles:
- [Initializing Arrays in Java](https://www.baeldung.com/java-initialize-array)
- [Array Operations in Java](https://www.baeldung.com/java-common-array-operations)
- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list)
- [Check if a Java Array Contains a Value](https://www.baeldung.com/java-array-contains-value)
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Extending an Arrays Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [[More advanced operations -->]](/core-java-modules/core-java-arrays-operations-advanced)

View File

@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-arrays-operations-basic</artifactId>
<name>core-java-arrays-operations-basic</name>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- Benchmarking -->
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<shade.plugin.version>3.2.0</shade.plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<jmh.version>1.19</jmh.version>
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>

View File

@@ -0,0 +1,34 @@
package com.baeldung.array;
import java.util.ArrayList;
import java.util.Arrays;
public class AddElementToEndOfArray {
public Integer[] addElementUsingArraysCopyOf(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = Arrays.copyOf(srcArray, srcArray.length + 1);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
public Integer[] addElementUsingArrayList(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(srcArray));
arrayList.add(elementToAdd);
return arrayList.toArray(destArray);
}
public Integer[] addElementUsingSystemArrayCopy(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
System.arraycopy(srcArray, 0, destArray, 0, srcArray.length);
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.array;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class ArrayBenchmarkRunner {
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SearchArrayBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@@ -0,0 +1,78 @@
package com.baeldung.array;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayInitializer {
static int[] initializeArrayInLoop() {
int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
array[i] = i + 2;
}
return array;
}
static int[][] initializeMultiDimensionalArrayInLoop() {
int array[][] = new int[2][5];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
array[i][j] = j + 1;
}
}
return array;
}
static String[] initializeArrayAtTimeOfDeclarationMethod1() {
String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
return array;
}
static int[] initializeArrayAtTimeOfDeclarationMethod2() {
int[] array = new int[] { 1, 2, 3, 4, 5 };
return array;
}
static int[] initializeArrayAtTimeOfDeclarationMethod3() {
int array[] = { 1, 2, 3, 4, 5 };
return array;
}
static long[] initializeArrayUsingArraysFill() {
long array[] = new long[5];
Arrays.fill(array, 30);
return array;
}
static int[] initializeArrayRangeUsingArraysFill() {
int array[] = new int[5];
Arrays.fill(array, 0, 3, -50);
return array;
}
static int[] initializeArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);
return copy;
}
static int[] initializeLargerArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 6);
return copy;
}
static int[] initializeArrayUsingArraysSetAll() {
int[] array = new int[20];
Arrays.setAll(array, p -> p > 9 ? 0 : p);
return array;
}
static char[] initializeArrayUsingArraysUtilClone() {
char[] array = new char[] { 'a', 'b', 'c' };
return ArrayUtils.clone(array);
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.array;
import org.apache.commons.lang3.ArrayUtils;
public class RemoveElementFromAnArray {
public int[] removeAnElementWithAGivenIndex(int[] array, int index) {
return ArrayUtils.remove(array, index);
}
public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) {
return ArrayUtils.removeAll(array, indicies);
}
public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) {
return ArrayUtils.removeElement(array, element);
}
public int[] removeAllGivenElements(int[] array, int... elements) {
return ArrayUtils.removeElements(array, elements);
}
public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) {
return ArrayUtils.removeAllOccurences(array, element);
}
}

View File

@@ -0,0 +1,96 @@
package com.baeldung.array;
import org.openjdk.jmh.annotations.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class SearchArrayBenchmark {
@State(Scope.Benchmark)
public static class SearchData {
static int count = 1000;
static String[] strings = seedArray(1000);
}
@Benchmark
public void searchArrayLoop() {
for (int i = 0; i < SearchData.count; i++) {
searchLoop(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewList() {
for (int i = 0; i < SearchData.count; i++) {
searchList(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewSet() {
for (int i = 0; i < SearchData.count; i++) {
searchSet(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayReuseList() {
List<String> asList = Arrays.asList(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
asList.contains("T");
}
}
@Benchmark
public void searchArrayReuseSet() {
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
for (int i = 0; i < SearchData.count; i++) {
asSet.contains("T");
}
}
@Benchmark
public void searchArrayBinarySearch() {
Arrays.sort(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
Arrays.binarySearch(SearchData.strings, "T");
}
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private static String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
}

View File

@@ -0,0 +1,239 @@
package com.baeldung.array.operations;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class ArrayOperations {
// Get the first and last item of an array
public static <T> T getFirstObject(T[] array) {
return array[0];
}
public static int getFirstInt(int[] array) {
return array[0];
}
public static <T> T getLastObject(T[] array) {
return array[array.length - 1];
}
public static int getLastInt(int[] array) {
return array[array.length - 1];
}
// Append a new item to an array
public static <T> T[] appendObject(T[] array, T newItem) {
return ArrayUtils.add(array, newItem);
}
public static int[] appendInt(int[] array, int newItem) {
int[] newArray = Arrays.copyOf(array, array.length + 1);
newArray[newArray.length - 1] = newItem;
return newArray;
}
public static int[] appendIntWithUtils(int[] array, int newItem) {
return ArrayUtils.add(array, newItem);
}
// Compare two arrays to check if they have the same elements
public static <T> boolean compareObjectArrays(T[] array1, T[] array2) {
return Arrays.equals(array1, array2);
}
public static boolean compareIntArrays(int[] array1, int[] array2) {
return Arrays.equals(array1, array2);
}
// Deep Compare (for nested arrays)
public static <T> boolean deepCompareObjectArrayUsingArrays(T[][] array1, T[][] array2) {
// We can use Objects.deepEquals for a broader approach
return Arrays.deepEquals(array1, array2);
}
public static boolean deepCompareIntArrayUsingArrays(int[][] array1, int[][] array2) {
return Arrays.deepEquals(array1, array2);
}
// Check if array is empty
public static <T> boolean isEmptyObjectArrayUsingUtils(T[] array1) {
return ArrayUtils.isEmpty(array1);
}
public static boolean isEmptyIntArrayUsingUtils(int[] array1) {
return ArrayUtils.isEmpty(array1);
}
// Remove duplicates
public static Integer[] removeDuplicateObjects(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new HashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateInts(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new HashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Remove duplicates preserving the order
public static Integer[] removeDuplicateWithOrderObjectArray(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateWithOrderIntArray(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Print an array
public static String printObjectArray(Integer[] array) {
return ArrayUtils.toString(array);
}
public static String printObjectArray(Integer[][] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[][] array) {
return ArrayUtils.toString(array);
}
// Box or Unbox values
public static int[] unboxIntegerArray(Integer[] array) {
return ArrayUtils.toPrimitive(array);
}
public static Integer[] boxIntArray(int[] array) {
return ArrayUtils.toObject(array);
}
// Map array values
@SuppressWarnings("unchecked")
public static <T, U> U[] mapObjectArray(T[] array, Function<T, U> function, Class<U> targetClazz) {
U[] newArray = (U[]) Array.newInstance(targetClazz, array.length);
for (int i = 0; i < array.length; i++) {
newArray[i] = function.apply(array[i]);
}
return newArray;
}
public static String[] mapIntArrayToString(int[] array) {
return Arrays.stream(array)
.mapToObj(value -> String.format("Value: %s", value))
.toArray(String[]::new);
}
// Filter array values
public static Integer[] filterObjectArray(Integer[] array, Predicate<Integer> predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray(Integer[]::new);
}
public static int[] filterIntArray(int[] array, IntPredicate predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray();
}
// Insert item between others
public static int[] insertBetweenIntArray(int[] array, int... values) {
return ArrayUtils.insert(2, array, values);
}
@SuppressWarnings("unchecked")
public static <T> T[] insertBetweenObjectArray(T[] array, T... values) {
return ArrayUtils.insert(2, array, values);
}
// Shuffling arrays
public static int[] shuffleIntArray(int[] array) {
// we create a different array instance for testing purposes
int[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
public static <T> T[] shuffleObjectArray(T[] array) {
// we create a different array instance for testing purposes
T[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
// Get random number
public static int getRandomFromIntArray(int[] array) {
return array[new Random().nextInt(array.length)];
}
public static <T> T getRandomFromObjectArray(T[] array) {
return array[new Random().nextInt(array.length)];
}
public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(Arrays.asList(b)::contains)
.toArray(Integer[]::new);
}
public static Integer[] intersectionSet(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(Arrays.asList(b)::contains)
.distinct()
.toArray(Integer[]::new);
}
public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b) {
return Stream.of(a)
.filter(new LinkedList<>(Arrays.asList(b))::remove)
.toArray(Integer[]::new);
}
public static Integer[] addElementUsingPureJava(Integer[] srcArray, int elementToAdd) {
Integer[] destArray = new Integer[srcArray.length + 1];
for (int i = 0; i < srcArray.length; i++) {
destArray[i] = srcArray[i];
}
destArray[destArray.length - 1] = elementToAdd;
return destArray;
}
public static int[] insertAnElementAtAGivenIndex(final int[] srcArray, int index, int newElement) {
int[] destArray = new int[srcArray.length + 1];
int j = 0;
for (int i = 0; i < destArray.length - 1; i++) {
if (i == index) {
destArray[i] = newElement;
} else {
destArray[i] = srcArray[j];
j++;
}
}
return destArray;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.arraylist.operations;
import java.util.ArrayList;
public class ArrayListOperations {
public static Integer getAnIntegerElement(ArrayList<Integer> anArrayList, int index) {
return anArrayList.get(index);
}
public static void modifyAnIntegerElement(ArrayList<Integer> anArrayList, int index, Integer newElement) {
anArrayList.set(index, newElement);
}
public static void appendAnIntegerElement(ArrayList<Integer> anArrayList, Integer newElement) {
anArrayList.add(newElement);
}
public static void insertAnIntegerElementAtIndex(ArrayList<Integer> anArrayList, int index, Integer newElement) {
anArrayList.add(index, newElement);
}
}

View File

@@ -0,0 +1,49 @@
package com.baeldung.array;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class AddElementToEndOfArrayUnitTest {
AddElementToEndOfArray addElementToEndOfArray;
@Before
public void init() {
addElementToEndOfArray = new AddElementToEndOfArray();
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArraysCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArraysCopyOf(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingArrayListIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingArrayList(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingSystemArrayCopyIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = {1, 2, 3, 4};
int elementToAdd = 5;
Integer[] destArray = addElementToEndOfArray.addElementUsingSystemArrayCopy(sourceArray, elementToAdd);
Integer[] expectedArray = {1, 2, 3, 4, 5};
assertArrayEquals(expectedArray, destArray);
}
}

View File

@@ -0,0 +1,74 @@
package com.baeldung.array;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod1;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod2;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod3;
import static com.baeldung.array.ArrayInitializer.initializeArrayInLoop;
import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysUtilClone;
import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ArrayInitializerUnitTest {
@Test
public void whenInitializeArrayInLoop_thenCorrect() {
assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop());
}
@Test
public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() {
assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3());
}
@Test
public void whenInitializeArrayUsingArraysFill_thenCorrect() {
assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() {
assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() {
assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll());
}
@Test
public void whenInitializeArrayUsingArraysUtilClone_thenCorrect() {
assertArrayEquals(new char[] { 'a', 'b', 'c' }, initializeArrayUsingArraysUtilClone());
}
}

View File

@@ -0,0 +1,82 @@
package com.baeldung.array;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class RemoveElementFromAnArrayUnitTest {
private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray();
private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 };
@Test
void testRemoveAnElementWithAGivenIndex() {
int index = 2;
int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index]));
}
@Test
void testRemoveAllElementsWithGivenIndices() {
int first = 0;
int last = inputArray.length - 1;
int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last);
assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last]));
}
@Test
void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() {
int index = 2;
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAnElementWithAGivenIndex(null, index);
});
assertThrows(IndexOutOfBoundsException.class, () -> {
sut.removeAllElementsWithGivenIndices(null, index);
});
}
@Test
void testRemoveFirstOccurrenceOfGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element);
int indexInInputArray = ArrayUtils.indexOf(inputArray, element);
int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element);
assertFalse(indexInInputArray == indexInModifiedArray);
}
@Test
void testRemoveAllGivenElements() {
int duplicateElement = 40;
int[] elements = new int[] { duplicateElement, 10, 50 };
int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements);
assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement));
assertFalse(ArrayUtils.contains(modifiedArray, elements[1]));
assertFalse(ArrayUtils.contains(modifiedArray, elements[2]));
}
@Test
void testRemoveAllOccurrencesOfAGivenElement() {
int element = 40;
int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element);
assertFalse(ArrayUtils.contains(modifiedArray, element));
}
@Test
void testRemoveElement_WhenArrayIsNull_ReturnsNull() {
int element = 20;
assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element));
assertEquals(null, sut.removeAllGivenElements(null, element));
assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element));
}
}

View File

@@ -0,0 +1,380 @@
package com.baeldung.array.operations;
import java.util.Arrays;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertArrayEquals;
public class ArrayOperationsUnitTest {
private Integer[] defaultObjectArray;
private int[] defaultIntArray;
private Integer[][] defaultJaggedObjectArray;
private int[][] defaultJaggedIntArray;
@BeforeEach
public void setupDefaults() {
defaultObjectArray = new Integer[] { 3, 5, 2, 5, 14, 4 };
defaultIntArray = new int[] { 3, 5, 2, 5, 14, 4 };
defaultJaggedObjectArray = new Integer[][] { { 1, 3 }, { 5 }, {} };
defaultJaggedIntArray = new int[][] { { 1, 3 }, { 5 }, {} };
}
// Get the first and last item of an array
@Test
public void whenGetFirstObjectCalled_thenReturnFirstItemOfArray() {
Integer output = ArrayOperations.getFirstObject(defaultObjectArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetFirstIntCalled_thenReturnFirstItemOfArray() {
int output = ArrayOperations.getFirstInt(defaultIntArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetLastObjectCalled_thenReturnLastItemOfArray() {
Integer output = ArrayOperations.getLastObject(defaultObjectArray);
assertThat(output).isEqualTo(4);
}
@Test
public void whenGetLastIntCalled_thenReturnLastItemOfArray() {
int output = ArrayOperations.getLastInt(defaultIntArray);
assertThat(output).isEqualTo(4);
}
// Append a new item to an array
@Test
public void whenAppendObject_thenReturnArrayWithExtraItem() {
Integer[] output = ArrayOperations.appendObject(defaultObjectArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
}
@Test
public void whenAppendInt_thenReturnArrayWithExtraItem() {
int[] output = ArrayOperations.appendInt(defaultIntArray, 7);
int[] outputUsingUtils = ArrayOperations.appendIntWithUtils(defaultIntArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
assertThat(outputUsingUtils).endsWith(4, 7)
.hasSize(7);
}
// Compare two arrays to check if they have the same elements
@Test
public void whenCompareObjectArrays_thenReturnBoolean() {
Integer[] array2 = { 8, 7, 6 };
Integer[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareObjectArrays(defaultObjectArray, array2);
boolean output2 = ArrayOperations.compareObjectArrays(defaultObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
@Test
public void whenCompareIntArrays_thenReturnBoolean() {
int[] array2 = { 8, 7, 6 };
int[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareIntArrays(defaultIntArray, array2);
boolean output2 = ArrayOperations.compareIntArrays(defaultIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Deep compare
@Test
public void whenDeepCompareObjectArrays_thenReturnBoolean() {
Integer[][] sameArray = { { 1, 3 }, { 5 }, {} };
Integer[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, array2);
boolean output2 = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, sameArray);
// Because arrays are Objects, we could wrongly use the non-deep approach
boolean outputUsingNonDeep = ArrayOperations.compareObjectArrays(defaultJaggedObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
// This is not what we would expect!
assertThat(outputUsingNonDeep).isFalse();
}
@Test
public void whenDeepCompareIntArrays_thenReturnBoolean() {
int[][] sameArray = { { 1, 3 }, { 5 }, {} };
int[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, array2);
boolean output2 = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Empty Check
@Test
public void whenIsEmptyObjectArray_thenReturnBoolean() {
Integer[] array2 = {};
Integer[] array3 = null;
Integer[] array4 = { null, null, null };
Integer[] array5 = { null };
Integer[][] array6 = { {}, {}, {} };
boolean output = ArrayOperations.isEmptyObjectArrayUsingUtils(defaultObjectArray);
boolean output2 = ArrayOperations.isEmptyObjectArrayUsingUtils(array2);
boolean output3 = ArrayOperations.isEmptyObjectArrayUsingUtils(array3);
boolean output4 = ArrayOperations.isEmptyObjectArrayUsingUtils(array4);
boolean output5 = ArrayOperations.isEmptyObjectArrayUsingUtils(array5);
boolean output6 = ArrayOperations.isEmptyObjectArrayUsingUtils(array6);
assertThat(output).isFalse();
assertThat(output2).isTrue();
assertThat(output3).isTrue();
// Mind these edge cases!
assertThat(output4).isFalse();
assertThat(output5).isFalse();
assertThat(output6).isFalse();
}
@Test
public void whenIsEmptyIntArray_thenReturnBoolean() {
int[] array2 = {};
boolean output = ArrayOperations.isEmptyIntArrayUsingUtils(defaultIntArray);
boolean output2 = ArrayOperations.isEmptyIntArrayUsingUtils(array2);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Remove Duplicates
@Test
public void whenRemoveDuplicateObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] output = ArrayOperations.removeDuplicateObjects(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
@Test
public void whenRemoveDuplicateIntArray_thenReturnArrayWithNoDuplicates() {
int[] output = ArrayOperations.removeDuplicateInts(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
// Remove Duplicates Preserving order
@Test
public void whenRemoveDuplicatePreservingOrderObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] array2 = { 3, 5, 2, 14, 4 };
Integer[] output = ArrayOperations.removeDuplicateWithOrderObjectArray(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
@Test
public void whenRemoveDuplicatePreservingOrderIntArray_thenReturnArrayWithNoDuplicates() {
int[] array2 = { 3, 5, 2, 14, 4 };
int[] output = ArrayOperations.removeDuplicateWithOrderIntArray(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
// Print
@Test
public void whenPrintObjectArray_thenReturnString() {
String output = ArrayOperations.printObjectArray(defaultObjectArray);
String jaggedOutput = ArrayOperations.printObjectArray(defaultJaggedObjectArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
// We should use Arrays.deepToString for jagged arrays
String differentFormatJaggedArraysOutput = Arrays.deepToString(defaultJaggedObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
assertThat(differentFormatJaggedArraysOutput).contains("[[1, 3], [5], []]");
}
@Test
public void whenPrintIntArray_thenReturnString() {
String output = ArrayOperations.printIntArray(defaultIntArray);
String jaggedOutput = ArrayOperations.printIntArray(defaultJaggedIntArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
}
// Box and unbox
@Test
public void whenUnboxObjectArray_thenReturnPrimitiveArray() {
int[] output = ArrayOperations.unboxIntegerArray(defaultObjectArray);
assertThat(output).containsExactly(defaultIntArray);
}
@Test
public void henBoxPrimitiveArray_thenReturnObjectArray() {
Integer[] output = ArrayOperations.boxIntArray(defaultIntArray);
assertThat(output).containsExactly(defaultObjectArray);
}
// Map values
@Test
public void whenMapMultiplyingObjectArray_thenReturnMultipliedArray() {
Integer[] multipliedExpectedArray = new Integer[] { 6, 10, 4, 10, 28, 8 };
Integer[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value * 2, Integer.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapDividingObjectArray_thenReturnDividedArray() {
Double[] multipliedExpectedArray = new Double[] { 1.5, 2.5, 1.0, 2.5, 7.0, 2.0 };
Double[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value / 2.0, Double.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapIntArrayToString_thenReturnArray() {
String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14", "Value: 4" };
String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray);
assertThat(output).containsExactly(expectedArray);
}
// Filter values
@Test
public void whenFilterObjectArray_thenReturnFilteredArray() {
Integer[] multipliedExpectedArray = new Integer[] { 2, 14, 4 };
Integer[] output = ArrayOperations.filterObjectArray(defaultObjectArray, value -> value % 2 == 0);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenFilterIntArray_thenReturnFilteredArray() {
int[] expectedArray = new int[] { 2, 14, 4 };
int[] output = ArrayOperations.filterIntArray(defaultIntArray, value -> (int) value % 2 == 0);
assertThat(output).containsExactly(expectedArray);
}
// Insert between
@Test
public void whenInsertBetweenIntArrayToString_thenReturnNewArray() {
int[] expectedArray = { 3, 5, 77, 88, 2, 5, 14, 4 };
int[] output = ArrayOperations.insertBetweenIntArray(defaultIntArray, 77, 88);
assertThat(output).containsExactly(expectedArray);
}
@Test
public void whenInsertBetweenObjectArrayToString_thenReturnNewArray() {
Integer[] expectedArray = { 3, 5, 77, 99, 2, 5, 14, 4 };
Integer[] output = ArrayOperations.insertBetweenObjectArray(defaultObjectArray, 77, 99);
assertThat(output).containsExactly(expectedArray);
}
// Shuffle between
@Test
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);
Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>("at least one output should be different (order-wise)") {
@Override
public boolean matches(int[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
}
};
assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
}
@Test
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>("at least one output should be different (order-wise)") {
@Override
public boolean matches(Integer[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3) || !Arrays.equals(value, output4) || !Arrays.equals(value, output5) || !Arrays.equals(value, output6);
}
};
assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
}
// Get random item
@Test
public void whenGetRandomFromIntArrayToString_thenReturnItemContainedInArray() {
int output = ArrayOperations.getRandomFromIntArray(defaultIntArray);
assertThat(defaultIntArray).contains(output);
}
@Test
public void whenGetRandomFromObjectArrayToString_thenReturnItemContainedInArray() {
Integer output = ArrayOperations.getRandomFromObjectArray(defaultObjectArray);
assertThat(defaultObjectArray).contains(output);
}
@Test
public void givenSourceArrayAndElement_whenAddElementUsingPureJavaIsInvoked_thenNewElementMustBeAdded() {
Integer[] sourceArray = { 1, 2, 3, 4 };
int elementToAdd = 5;
Integer[] destArray = ArrayOperations.addElementUsingPureJava(sourceArray, elementToAdd);
Integer[] expectedArray = { 1, 2, 3, 4, 5 };
assertArrayEquals(expectedArray, destArray);
}
@Test
public void whenInsertAnElementAtAGivenIndexCalled_thenShiftTheFollowingElementsAndInsertTheElementInArray() {
int[] expectedArray = { 1, 4, 2, 3, 0 };
int[] anArray = new int[4];
anArray[0] = 1;
anArray[1] = 2;
anArray[2] = 3;
int[] outputArray = ArrayOperations.insertAnElementAtAGivenIndex(anArray, 1, 4);
assertThat(outputArray).containsExactly(expectedArray);
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.array.removefirst;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class RemoveFirstElementUnitTest {
private List<String> list = new ArrayList<>();
private LinkedList<String> linkedList = new LinkedList<>();
@Before
public void init() {
list.add("cat");
list.add("dog");
list.add("pig");
list.add("cow");
list.add("goat");
linkedList.add("cat");
linkedList.add("dog");
linkedList.add("pig");
linkedList.add("cow");
linkedList.add("goat");
}
@Test
public void givenList_whenRemoveFirst_thenRemoved() {
list.remove(0);
assertThat(list, hasSize(4));
assertThat(list, not(contains("cat")));
}
@Test
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
linkedList.removeFirst();
assertThat(linkedList, hasSize(4));
assertThat(linkedList, not(contains("cat")));
}
@Test
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
assertThat(modifiedArray.length, is(2));
assertThat(modifiedArray[0], is("bar"));
}
}

View File

@@ -0,0 +1,50 @@
package com.baeldung.arraylist.operations;
import java.util.ArrayList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ArrayListOperationsUnitTest {
private ArrayList<Integer> anArrayList;
@BeforeEach
public void setupDefaults() {
anArrayList = new ArrayList<>();
anArrayList.add(2);
anArrayList.add(3);
anArrayList.add(4);
}
@Test
public void whenGetAnIntegerElementCalled_thenReturnTheIntegerElement() {
Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1);
assertThat(output).isEqualTo(3);
}
@Test
public void whenModifyAnIntegerElementCalled_thenModifyTheIntegerElement() {
ArrayListOperations.modifyAnIntegerElement(anArrayList, 2, 5);
Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 2);
assertThat(output).isEqualTo(5);
}
@Test
public void whenAppendAnIntegerElementCalled_thenTheIntegerElementIsAppendedToArrayList() {
ArrayListOperations.appendAnIntegerElement(anArrayList, 6);
Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, anArrayList.size() - 1);
assertThat(output).isEqualTo(6);
}
@Test
public void whenInsertAnIntegerAtIndexCalled_thenTheIntegerElementIsInseredToArrayList() {
ArrayListOperations.insertAnIntegerElementAtIndex(anArrayList, 1, 10);
Integer output = ArrayListOperations.getAnIntegerElement(anArrayList, 1);
assertThat(output).isEqualTo(10);
}
}