[JAVA-616] core-java-arrays-guides
* Creation * Moved code from https://www.baeldung.com/java-arrays-guide * Moved code from https://www.baeldung.com/java-util-arrays
This commit is contained in:
@@ -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,44 @@
|
||||
package com.baeldung.arrays;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ParallelPrefixBenchmark {
|
||||
private static final int ARRAY_SIZE = 200_000_000;
|
||||
|
||||
@State(Scope.Benchmark)
|
||||
public static class BigArray {
|
||||
|
||||
int[] data;
|
||||
|
||||
@Setup(Level.Iteration)
|
||||
public void prepare() {
|
||||
data = new int[ARRAY_SIZE];
|
||||
for(int j = 0; j< ARRAY_SIZE; j++) {
|
||||
data[j] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@TearDown(Level.Iteration)
|
||||
public void destroy() {
|
||||
data = null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) {
|
||||
for (int i = 0; i < ARRAY_SIZE - 1; i++) {
|
||||
bigArray.data[i + 1] += bigArray.data[i];
|
||||
}
|
||||
blackhole.consume(bigArray.data);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) {
|
||||
Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right);
|
||||
blackhole.consume(bigArray.data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.baeldung.arrays;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
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.Random;
|
||||
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");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntArray_whenPrefixAdd_thenAllAccumulated() {
|
||||
int[] arri = new int[] { 1, 2, 3, 4};
|
||||
Arrays.parallelPrefix(arri, (left, right) -> left + right);
|
||||
assertThat(arri, is(new int[] { 1, 3, 6, 10}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenPrefixConcat_thenAllMerged() {
|
||||
String[] arrs = new String[] { "1", "2", "3" };
|
||||
Arrays.parallelPrefix(arrs, (left, right) -> left + right);
|
||||
assertThat(arrs, is(new String[] { "1", "12", "123" }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixAddWithRange_thenRangeAdded() {
|
||||
int[] arri = new int[] { 1, 2, 3, 4, 5 };
|
||||
Arrays.parallelPrefix(arri, 1, 4, (left, right) -> left + right);
|
||||
assertThat(arri, is(new int[] { 1, 2, 5, 9, 5 }));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrefixNonAssociative_thenError() {
|
||||
boolean consistent = true;
|
||||
Random r = new Random();
|
||||
for (int k = 0; k < 100_000; k++) {
|
||||
int[] arrA = r.ints(100, 1, 5).toArray();
|
||||
int[] arrB = Arrays.copyOf(arrA, arrA.length);
|
||||
|
||||
Arrays.parallelPrefix(arrA, this::nonassociativeFunc);
|
||||
|
||||
for (int i = 1; i < arrB.length; i++) {
|
||||
arrB[i] = nonassociativeFunc(arrB[i - 1], arrB[i]);
|
||||
}
|
||||
consistent = Arrays.equals(arrA, arrB);
|
||||
if(!consistent) break;
|
||||
}
|
||||
assertFalse(consistent);
|
||||
}
|
||||
|
||||
/**
|
||||
* non-associative int binary operator
|
||||
*/
|
||||
private int nonassociativeFunc(int left, int right) {
|
||||
return left + right*left;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user