geroza
2018-11-10 11:13:04 -02:00
parent 55c49b25f1
commit 7249a2c88d
44 changed files with 572 additions and 0 deletions

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,49 @@
package com.baeldung.array;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ArrayInverterUnitTest {
private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" };
@Test
public void invertArrayWithForLoop() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingFor(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithCollectionsReverse() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingCollectionsReverse(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithStreams() {
ArrayInverter inverter = new ArrayInverter();
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits));
}
@Test
public void invertArrayWithCommonsLang() {
ArrayInverter inverter = new ArrayInverter();
inverter.invertUsingCommonsLang(fruits);
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
}
@Test
public void invertArrayWithGuava() {
ArrayInverter inverter = new ArrayInverter();
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits));
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class Find2ndLargestInArrayUnitTest {
@Test
public void givenAnIntArray_thenFind2ndLargestElement() {
int[] array = { 1, 3, 24, 16, 87, 20 };
int expected2ndLargest = 24;
int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class FindElementInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int element = 19;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 78;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
int[] array = { 15, 16, 12, 18 };
int element = 16;
boolean expectedResult = true;
boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
element = 20;
expectedResult = false;
actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
Assert.assertEquals(expectedResult, actualResult);
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.array;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.junit.Test;
public class JaggedArrayUnitTest {
private JaggedArray obj = new JaggedArray();
@Test
public void whenInitializedUsingShortHandForm_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization());
}
@Test
public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() {
InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes());
System.setIn(is);
assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs());
System.setIn(System.in);
}
@Test
public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0));
assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1));
assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2));
}
@Test
public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() {
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
obj.printElements(jaggedArr);
assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out);
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.array;
import org.junit.Assert;
import org.junit.Test;
public class SumAndAverageInArrayUnitTest {
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindSum() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindSum() {
int[] array = { 1, 3, 4, 8, 19, 20 };
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() {
Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20};
int expectedSumOfArray = 55;
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
}
@Test
public void givenAnIntArray_whenNotUsingStream_thenFindAverage() {
int[] array = { 1, 3, 4, 8, 19, 20 };
double expectedAvgOfArray = 9.17;
double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
}
@Test
public void givenAnIntArray_whenUsingStream_thenFindAverage() {
int[] array = { 1, 3, 4, 8, 19, 20 };
double expectedAvgOfArray = 9.17;
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
}
@Test
public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() {
int[] array = {};
double expectedAvgOfArray = Double.NaN;
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00);
}
}

View File

@@ -0,0 +1,365 @@
package com.baeldung.array.operations;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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);
}
}

View File

@@ -0,0 +1,170 @@
package com.baeldung.arraycopy;
import com.baeldung.arraycopy.model.Address;
import com.baeldung.arraycopy.model.Employee;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
public class ArrayCopyUtilUnitTest {
private static Employee[] employees;
private static final int MAX = 2;
@BeforeClass
public static void setup(){
createEmployeesArray();
}
private static void createEmployeesArray() {
employees = new Employee[MAX];
Employee employee;
for(int i = 0; i < MAX; i++) {
employee = new Employee();
employee.setName("Emp"+i);
employee.setId(i);
employees[i] = employee;
}
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55};
int[] copiedArray = new int[3];
System.arraycopy(array, 0, copiedArray, 0, 3);
Assert.assertArrayEquals(copiedArray, array);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = new int[3];
System.arraycopy(array, 2, copiedArray, 0, 3);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[2]);
assertTrue(copiedArray[1] == array[3]);
assertTrue(copiedArray[2] == array[4]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
assertTrue(3 == copiedArray.length);
assertTrue(copiedArray[0] == array[1]);
assertTrue(copiedArray[1] == array[2]);
assertTrue(copiedArray[2] == array[3]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Employee[] copiedArray = employees.clone();
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Address[] addresses = createAddressArray();
Address[] copiedArray = addresses.clone();
addresses[0].setCity(addresses[0].getCity()+"_Changed");
Assert.assertArrayEquals(copiedArray, addresses);
}
@Test
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
Employee[] copiedArray = SerializationUtils.clone(employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertFalse(
copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
String[] strArray = {"orange", "red", "green'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
Assert.assertArrayEquals(copiedArray, strArray);
}
private Address[] createAddressArray(){
Address[] addresses = new Address[1];
addresses[0] = createAddress();
return addresses;
}
private Address createAddress() {
Address address = new Address();
address.setCountry("USA");
address.setState("CA");
address.setCity("San Francisco");
address.setStreet("Street 1");
address.setZipcode("59999");
return address;
}
}

View File

@@ -0,0 +1,153 @@
package com.baeldung.arrays;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ArraysUnitTest {
private String[] intro;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
intro = new String[] { "once", "upon", "a", "time" };
}
@Test
public void whenCopyOfRange_thenAbridgedArray() {
String[] abridgement = Arrays.copyOfRange(intro, 0, 3);
assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement);
assertFalse(Arrays.equals(intro, abridgement));
}
@Test
public void whenCopyOf_thenNullElement() {
String[] revised = Arrays.copyOf(intro, 3);
String[] expanded = Arrays.copyOf(intro, 5);
assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
assertNull(expanded[4]);
}
@Test
public void whenFill_thenAllMatch() {
String[] stutter = new String[3];
Arrays.fill(stutter, "once");
assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el)));
}
@Test
public void whenEqualsContent_thenMatch() {
assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro));
}
@Test
public void whenNestedArrays_thenDeepEqualsPass() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertTrue(Arrays.deepEquals(story, copy));
assertFalse(Arrays.equals(story, copy));
}
@Test
public void whenSort_thenArraySorted() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted);
}
@Test
public void whenBinarySearch_thenFindElements() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
int exact = Arrays.binarySearch(sorted, "time");
int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);
assertEquals("time", sorted[exact]);
assertEquals(2, exact);
assertEquals(exact, caseInsensitive);
}
@Test
public void whenNullElement_thenArraysHashCodeNotEqual() {
int beforeChange = Arrays.hashCode(intro);
int before = intro.hashCode();
intro[3] = null;
int after = intro.hashCode();
int afterChange = Arrays.hashCode(intro);
assertNotEquals(beforeChange, afterChange);
assertEquals(before, after);
}
@Test
public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() {
Object[] looping = new Object[] { intro, intro };
int deepHashBefore = Arrays.deepHashCode(looping);
int hashBefore = Arrays.hashCode(looping);
intro[3] = null;
int hashAfter = Arrays.hashCode(looping);
int deepHashAfter = Arrays.deepHashCode(looping);
assertEquals(hashAfter, hashBefore);
assertNotEquals(deepHashAfter, deepHashBefore);
}
@Test
public void whenStreamBadIndex_thenException() {
assertEquals(Arrays.stream(intro).count(), 4);
exception.expect(ArrayIndexOutOfBoundsException.class);
Arrays.stream(intro, 2, 1).count();
}
@Test
public void whenSetAllToUpper_thenAppliedToAllElements() {
String[] longAgo = new String[4];
Arrays.setAll(longAgo, i -> intro[i].toUpperCase());
assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" });
}
@Test
public void whenToString_thenFormattedArrayString() {
assertEquals("[once, upon, a, time]", Arrays.toString(intro));
}
@Test
public void whenNestedArrayDeepString_thenFormattedArraysString() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story));
}
@Test
public void whenAsList_thenImmutableArray() {
List<String> rets = Arrays.asList(intro);
assertTrue(rets.contains("upon"));
assertTrue(rets.contains("time"));
assertEquals(rets.size(), 4);
exception.expect(UnsupportedOperationException.class);
rets.add("the");
}
}