5 - Fifth commit to split core-java. This one includes:
* to core-java-lang: * https://www.baeldung.com/java-separate-double-into-integer-decimal-parts * https://www.baeldung.com/java-sneaky-throws * https://www.baeldung.com/java-inheritance-composition * to core-java-array: * https://www.baeldung.com/java-array-copy * https://www.baeldung.com/java-initialize-array * https://www.baeldung.com/java-array-contains-value * https://www.baeldung.com/java-invert-array * https://www.baeldung.com/java-array-sum-average * https://www.baeldung.com/java-jagged-arrays * https://www.baeldung.com/java-util-arrays * https://www.baeldung.com/java-common-array-operations (from core-java-collections)
This commit is contained in:
@@ -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(SearchArrayUnitTest.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
|
||||
new Runner(options).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.lang.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ArrayInverter {
|
||||
|
||||
public void invertUsingFor(Object[] array) {
|
||||
for (int i = 0; i < array.length / 2; i++) {
|
||||
Object temp = array[i];
|
||||
array[i] = array[array.length - 1 - i];
|
||||
array[array.length - 1 - i] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
public void invertUsingCollectionsReverse(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
Collections.reverse(list);
|
||||
}
|
||||
|
||||
public Object[] invertUsingStreams(final Object[] array) {
|
||||
return IntStream.rangeClosed(1, array.length)
|
||||
.mapToObj(i -> array[array.length - i])
|
||||
.toArray();
|
||||
}
|
||||
|
||||
public void invertUsingCommonsLang(Object[] array) {
|
||||
ArrayUtils.reverse(array);
|
||||
}
|
||||
|
||||
public Object[] invertUsingGuava(Object[] array) {
|
||||
List<Object> list = Arrays.asList(array);
|
||||
List<Object> reverted = Lists.reverse(list);
|
||||
return reverted.toArray();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ArrayReferenceGuide {
|
||||
|
||||
public static void main(String[] args) {
|
||||
declaration();
|
||||
|
||||
initialization();
|
||||
|
||||
access();
|
||||
|
||||
iterating();
|
||||
|
||||
varargs();
|
||||
|
||||
transformIntoList();
|
||||
|
||||
transformIntoStream();
|
||||
|
||||
sort();
|
||||
|
||||
search();
|
||||
|
||||
merge();
|
||||
}
|
||||
|
||||
private static void declaration() {
|
||||
int[] anArray;
|
||||
int anotherArray[];
|
||||
}
|
||||
|
||||
private static void initialization() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
}
|
||||
|
||||
private static void access() {
|
||||
int[] anArray = new int[10];
|
||||
anArray[0] = 10;
|
||||
anArray[5] = 4;
|
||||
|
||||
System.out.println(anArray[0]);
|
||||
}
|
||||
|
||||
private static void iterating() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
System.out.println(anArray[i]);
|
||||
}
|
||||
|
||||
for (int element : anArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void varargs() {
|
||||
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
|
||||
varargMethod(groceries);
|
||||
varargMethod("Milk", "Tomato", "Chips");
|
||||
}
|
||||
|
||||
private static void varargMethod(String... varargs) {
|
||||
for (String element : varargs) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
private static void transformIntoList() {
|
||||
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
|
||||
// Naïve implementation
|
||||
List<Integer> aList = new ArrayList<>(); // We create an empty list
|
||||
for (int element : anArray) {
|
||||
// We iterate over array's elements and add them to the list
|
||||
aList.add(element);
|
||||
}
|
||||
|
||||
// Pretty implementation
|
||||
aList = Arrays.asList(anArray);
|
||||
|
||||
// Drawbacks
|
||||
try {
|
||||
aList.remove(0);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
aList.add(6);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
|
||||
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||
// List<Integer> anotherList = Arrays.asList(anotherArray);
|
||||
}
|
||||
|
||||
private static void transformIntoStream() {
|
||||
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||
IntStream aStream = Arrays.stream(anArray);
|
||||
|
||||
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
|
||||
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
|
||||
}
|
||||
|
||||
private static void sort() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
|
||||
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
|
||||
|
||||
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
|
||||
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
|
||||
}
|
||||
|
||||
private static void search() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
for (int i = 0; i < anArray.length; i++) {
|
||||
if (anArray[i] == 4) {
|
||||
System.out.println("Found at index " + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Arrays.sort(anArray);
|
||||
int index = Arrays.binarySearch(anArray, 4);
|
||||
System.out.println("Found at index " + index);
|
||||
}
|
||||
|
||||
private static void merge() {
|
||||
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
|
||||
|
||||
int[] resultArray = new int[anArray.length + anotherArray.length];
|
||||
for (int i = 0; i < resultArray.length; i++) {
|
||||
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
|
||||
}
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
|
||||
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
|
||||
for (int element : resultArray) {
|
||||
System.out.println(element);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
public class Find2ndLargestInArray {
|
||||
|
||||
public static int find2ndLargestElement(int[] array) {
|
||||
int maxElement = array[0];
|
||||
int secondLargestElement = -1;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (maxElement <= array[index]) {
|
||||
secondLargestElement = maxElement;
|
||||
maxElement = array[index];
|
||||
} else if (secondLargestElement < array[index]) {
|
||||
secondLargestElement = array[index];
|
||||
}
|
||||
}
|
||||
return secondLargestElement;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class FindElementInArray {
|
||||
|
||||
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
|
||||
boolean actualResult = false;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (element == array[index]) {
|
||||
actualResult = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return actualResult;
|
||||
}
|
||||
|
||||
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
|
||||
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class JaggedArray {
|
||||
|
||||
int[][] shortHandFormInitialization() {
|
||||
int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } };
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
int[][] declarationAndThenInitialization() {
|
||||
int[][] jaggedArr = new int[3][];
|
||||
jaggedArr[0] = new int[] { 1, 2 };
|
||||
jaggedArr[1] = new int[] { 3, 4, 5 };
|
||||
jaggedArr[2] = new int[] { 6, 7, 8, 9 };
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
int[][] declarationAndThenInitializationUsingUserInputs() {
|
||||
int[][] jaggedArr = new int[3][];
|
||||
jaggedArr[0] = new int[2];
|
||||
jaggedArr[1] = new int[3];
|
||||
jaggedArr[2] = new int[4];
|
||||
initializeElements(jaggedArr);
|
||||
return jaggedArr;
|
||||
}
|
||||
|
||||
void initializeElements(int[][] jaggedArr) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
for (int outer = 0; outer < jaggedArr.length; outer++) {
|
||||
for (int inner = 0; inner < jaggedArr[outer].length; inner++) {
|
||||
jaggedArr[outer][inner] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void printElements(int[][] jaggedArr) {
|
||||
for (int index = 0; index < jaggedArr.length; index++) {
|
||||
System.out.println(Arrays.toString(jaggedArr[index]));
|
||||
}
|
||||
}
|
||||
|
||||
int[] getElementAtGivenIndex(int[][] jaggedArr, int index) {
|
||||
return jaggedArr[index];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 SearchArrayUnitTest {
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SumAndAverageInArray {
|
||||
|
||||
public static int findSumWithoutUsingStream(int[] array) {
|
||||
int sum = 0;
|
||||
for (int value : array) {
|
||||
sum += value;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(int[] array) {
|
||||
return Arrays.stream(array).sum();
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(Integer[] array) {
|
||||
return Arrays.stream(array).mapToInt(Integer::intValue).sum();
|
||||
}
|
||||
|
||||
public static double findAverageWithoutUsingStream(int[] array) {
|
||||
int sum = findSumWithoutUsingStream(array);
|
||||
return (double) sum / array.length;
|
||||
}
|
||||
|
||||
public static double findAverageUsingStream(int[] array) {
|
||||
return Arrays.stream(array).average().orElse(Double.NaN);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.baeldung.array.operations;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
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)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
public class Address implements Cloneable {
|
||||
private String country;
|
||||
private String state;
|
||||
private String city;
|
||||
private String street;
|
||||
private String zipcode;
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public String getZipcode() {
|
||||
return zipcode;
|
||||
}
|
||||
|
||||
public void setZipcode(String zipcode) {
|
||||
this.zipcode = zipcode;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
super.clone();
|
||||
Address address = new Address();
|
||||
address.setCity(this.city);
|
||||
address.setCountry(this.country);
|
||||
address.setState(this.state);
|
||||
address.setStreet(this.street);
|
||||
address.setZipcode(this.zipcode);
|
||||
return address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.arraycopy.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Employee implements Serializable {
|
||||
private static final long serialVersionUID = -2454619097207585825L;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user